簡體   English   中英

如何在QDialog中顯示QMainWindow

[英]How to show a QMainWindow inside a QDialog

我正在嘗試在QDialog中顯示QMainWindow,但前者不會出現。

我已經將QDialog子類化了,我們稱之為myDialog

一個小例子:

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);
}

如果執行對話框,則只會看到按鈕,而不會看到嵌入的QMainWindow。 如果我強制顯示qmainwindow,則主窗口將顯示在另一個窗口中。

使用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"

我認為Qt框架不支持此功能,根據他們在提供的文檔,該功能只能在應用程序中使用一次。

我的建議是將所有MainWindow實現以單獨的形式(繼承QWidget ),然后使用類似p_MainWindow->setCentralWidget(p_YourNewForm);形式將該形式添加到構造函數中的MainWindow中p_MainWindow->setCentralWidget(p_YourNewForm);

我已經能夠做到。

訣竅是構造沒有父對象的QMainWindow,然后應用.setParent

方法如下:

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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM