无法从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);
}
此代码仅在其中生成一个父窗口和一个子窗口.
This code just produces a parent window and a child window in it.
在末尾添加setLayout(gridLayout);
会产生以下错误:
Adding setLayout(gridLayout);
at the end of it produces following error:
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 already a fixed layout. So you cannot reassign one. See here: http://doc.qt.io/qt-5/qmainwindow.html#details
QMainWindow具有自己的布局,您可以在其中添加QToolBars, QDockWidgets,QMenuBar和QStatusBar.布局有一个中心 可以被任何类型的小部件占据的区域.
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.
您可以做的是将空"窗口小部件设置为中央窗口小部件并为其提供布局.
What you can do is set an "empty" widget as central widget and give it the layout.
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在评论中提到的:将小部件添加到布局中时,它将承担该项目的责任(使它们成为父项).因此,当您将项目添加到布局时,您不需要首先声明一个父项.
As @thuga mentioned in the comments: when you add a widget to the layout it will take the responsibility of the item (reparent them). So when you add the items to the layout you don't need to declare a parent in the first place.
您提供给setCentralWidget
这篇关于无法从MainWindow在QGridLayout中显示小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!