How to show a QMainWindow inside a QDialog

I am trying to show a QMainWindow inside a QDialog but the former does not appear.

I have subclassed QDialog, let's call it myDialog

A small example:

myDialog(QWidget *p_parent) : QDialog(p_parent)
{
    QGridLayout *p_dialogLayout = new QGridLayout(this);

    QMainWindow *p_MainWindow = new QMainWindow(this);
    QLabel *p_label = new QLabel(this);
    p_MainWindow->setCentralWidget(p_label);

    QPushButton *p_cancel = new QPushButton("Cancel", this);

    p_dialogLayout ->addWidget(p_MainWindow, 0, 0);
    p_dialogLayout ->addWidget(p_cancel, 1, 0);
}

If I execute the dialog, I only see the button, not the embeded QMainWindow. If i force to show the qmainwindow, the mainwindow is shown in another window.


使用QLayout::setMenuBar在对话框中添加一个工具栏。

#include <QtWidgets>

class Dialog : public QDialog
{
    Q_OBJECT
public:
    Dialog(QWidget *parent = nullptr) : QDialog(parent)
    {
        resize(600, 400);
        setLayout(new QHBoxLayout);
        QToolBar *toolbar = new QToolBar;
        toolbar->addAction("Action one");
        toolbar->addAction("Action two");
        layout()->setMenuBar(toolbar);

        layout()->addWidget(new QLabel("Label one"));
        layout()->addWidget(new QLabel("Label two"));
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}

#include "main.moc"

I don't think this is supported by the Qt framework, according to their documentation from here, it's intended to be used only once in an application.

My suggestion would be to take all your MainWindow implementation in a separate form (inheriting QWidget ), and just add that form to your MainWindow in the constructor using something like p_MainWindow->setCentralWidget(p_YourNewForm);


I have been able to do it.

The trick is to construct the QMainWindow without a parent, and then apply the .setParent

Here is how:

myDialog(QWidget *p_parent) : QDialog(p_parent)
{
    QGridLayout *p_dialogLayout = new QGridLayout(this); 

    QMainWindow *p_MainWindow = new QMainWindow(); //Without a parent
    QLabel *p_label = new QLabel(this);
    p_MainWindow->setCentralWidget(p_label);

    QPushButton *p_cancel = new QPushButton("Cancel", this);

    p_dialogLayout ->addWidget(p_MainWindow, 0, 0);
    p_dialogLayout ->addWidget(p_cancel, 1, 0);

    p_MainWindow->setParent(this); //Set the parent, to delete the MainWindow when the dialog is deleted.
}
链接地址: http://www.djcxy.com/p/39286.html

上一篇: Qt中我的课程名称应该以'Q'开头吗?

下一篇: 如何在QDialog中显示QMainWindow