无法从 MainWindow 在 QGridLayout 中显示小部件

Not able to display widgets in QGridLayout from MainWindow

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

此代码仅在其中生成一个父项 window 和一个子项 window。

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

QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout

不对的地方请指出

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.

您可以做的是将 "empty" 小部件设置为中央小部件并为其指定布局。

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

的小部件也是如此