Qt - 在我的MainWindow上调用setLayout()时编译器会抱怨

Dav*_*log 5 c++ layout qt

我想学习如何在没有设计师的情况下手工制作gui.我尝试为我添加一个布局,MainWindow但在运行时说

QWidget :: setLayout:试图在MainWindow上设置QLayout"",它已经有了一个布局

这是我的代码:

//Header
class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    QHBoxLayout *layout;
};

//Constructor in my *.cpp
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    layout = new QHBoxLayout;
    this->setLayout(layout);
}

//The usual main function
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

怎么了?我做了我的书所说的.我甚至在互联网上查找了一些代码很难找到的代码,它仍然是相同的.我只是无法在窗口中添加布局.

Dav*_*log 19

There's a similar question which helped me find out what's wrong. Thanks to Mat for his link to that question.

What every QMainWindow needs is a QWidget as central widget. I also created a new Project with the designer, compiled it and looked the ui_*.h files up.

So every QMainWindow should look similar to this :

//Header
class MainWindow : public QMainWindow
{
    Q_OBJECT
    QWidget *centralWidget;
    QGridLayout* gridLayout;

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:

};

//*.cpp
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    centralWidget = new QWidget(this);
    this->setCentralWidget( centralWidget );
    gridLayout = new QGridLayout( centralWidget );
}
Run Code Online (Sandbox Code Playgroud)

Now you don't add/set the layout to the MainWindow. You add/set it to the centralWidget.