无法在MainWindow

时间:2016-10-10 10:15:33

标签: 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: Attempting to set QLayout "" on MainWindow "", which already has a layout

请指出错误的行为。

1 个答案:

答案 0 :(得分:3)

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

  

QMainWindow有自己的布局,你可以添加QToolBars,   QDockWidgets,QMenuBar和QStatusBar。布局有一个中心   任何类型的小部件都可以占用的区域。

你可以做的是设置一个"空"小部件作为中央小部件并为其提供布局。

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

的小部件也是如此