【问题标题】:How to show a QMainWindow inside a QDialog如何在 QDialog 中显示 QMainWindow
【发布时间】:2017-02-21 11:07:35
【问题描述】:

我试图在 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,主窗口会显示在另一个窗口中。

【问题讨论】:

  • QMainWindow 是应用程序主窗口的一个类,为什么要将它放在对话框中?
  • @pablo_worker 了解他们如何在 Qt Designer 中做到这一点。
  • 我想放置一个qmainwindow来添加一个工具栏。 @SingerOfTheFall

标签: c++ qt


【解决方案1】:

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

【讨论】:

  • 谢谢!我不知道那个选项。一点不,不应该是 new QToolBar(this) 吗?自动删除它。 setMenuBar() 没有声明它拥有所有权。
  • @pablo_worker 您可以将this 作为父级传递,但setMenuBar 会自动执行。我知道,因为我检查了source code
【解决方案2】:

我认为 Qt 框架不支持这一点,根据他们来自 here 的文档,它只能在应用程序中使用一次。

我的建议是将您的所有 MainWindow 实现放在一个单独的表单中(继承 QWidget),然后使用类似 p_MainWindow-&gt;setCentralWidget(p_YourNewForm); 的东西将该表单添加到构造函数中的 MainWindow

【讨论】:

    【解决方案3】:

    我已经做到了。

    诀窍是在没有父级的情况下构造 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.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2017-11-24
      相关资源
      最近更新 更多