qt - 无法从 MainWindow 显示 QGridLayout 中的小部件

标签 qt widget grid-layout

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    reminderTextEdit     = new QTextEdit("");
    reminderTextEdit->setPlaceholderText("What do you want to be reminded of?");
    /// Setting parent is necessary otherwise it will be created in a window of its own.
    reminderTextEdit->setParent(this);
    reminderTextEdit->show();

    dateComboBox         = new QComboBox();
    dateComboBox->setParent(this);
    dateComboBox->show();

    monthComboBox        = new QComboBox();
    monthComboBox->setParent(this);
    monthComboBox->show();

    yearComboBox         = new QComboBox();
    yearComboBox->setParent(this);
    yearComboBox->show();

    doneAndAddMoreButton = new QPushButton();
    doneAndAddMoreButton->setParent(this);
    doneAndAddMoreButton->show();

    doneAndQuitButton    = new QPushButton();
    doneAndQuitButton->setParent(this);
    doneAndQuitButton->show();

    gridLayout           = new QGridLayout;
    gridLayout->addWidget(reminderTextEdit, 0, 0, 0, 0);
    gridLayout->addWidget(dateComboBox, 1, 0);
    gridLayout->addWidget(monthComboBox, 1, 1);
    gridLayout->addWidget(yearComboBox, 1, 2);
    gridLayout->addWidget(doneAndAddMoreButton, 2, 0);
    gridLayout->addWidget(doneAndQuitButton, 2, 1);
}

这段代码只是生成一个父窗口和一个子窗口。

在其末尾添加 setLayout(gridLayout); 会产生以下错误:

QWidget::setLayout:尝试在主窗口“”上设置 QLayout“”,该窗口已经有布局

错误的地方请指出。

最佳答案

QMainWindow 已经有固定的布局。所以你不能重新分配一个。参见这里:http://doc.qt.io/qt-5/qmainwindow.html#details

QMainWindow has its own layout to which you can add QToolBars, QDockWidgets, a QMenuBar, and a QStatusBar. The layout has a center area that can be occupied by any kind of widget.

您可以做的是将“空”小部件设置为中心小部件并为其指定布局。

QWidget *centralWidget = new QWidget(); //set parent to this
//...
reminderTextEdit = new QTextEdit("");
reminderTextEdit->setPlaceholderText("What do you want to be reminded of?");
//...

centralWidget->setLayout(gridLayout);    
setCentralWidget(window);

编辑:

正如 @thuga 在评论中提到的:当您将小部件添加到布局中时,它将承担该项目的责任(重新设置它们的父级)。因此,当您将项目添加到布局时,您不需要首先需要声明父级。

您提供给 setCentralWidget 的小部件也是如此

关于qt - 无法从 MainWindow 显示 QGridLayout 中的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39956017/

相关文章:

c++ - QMainWindow::splitDockWidget 的 QDockWidget 拉伸(stretch)因子?

c++ - 如何使用多个排序键对列表进行排序

c++ - 将自定义小部件显示到布局中

java - 将 JSlider 添加到具有 GridLayout 的 JFrame (Java)

Java 网格布局忽略间隙

qt - 如何在运行时确定 QtWebEngine 在 Qt 5 中使用哪个 Chrome 版本?

c++ - 如何将一个简单的 QSqlQueryModel 从一个类返回到另一个类?

user-interface - 在哪里可以找到 HTML 选择小部件的规范?

javascript - 如何使用 JavaScript 大致计算网站的连接速度?

Java:强制组件填满 GridLayout 中的整行