Not able to display widgets in QGridLayout from MainWindow

拥有回忆 提交于 2019-12-24 08:29:18

问题


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.

Adding setLayout(gridLayout); at the end of it produces following error:

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

Point out the wrong doings, please.


回答1:


QMainWindow has already a fixed layout. So you cannot reassign one. See here: 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.

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

EDIT:

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.

The same goes for the widget you provide to setCentralWidget



来源:https://stackoverflow.com/questions/39956017/not-able-to-display-widgets-in-qgridlayout-from-mainwindow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!