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/