Reputation: 2238
I wanna learn how to create a gui by hand without the designer. I tried to add a layout to my MainWindow
but when running it says
QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout
This is my code :
//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();
}
What is wrong? I did what my book said. I even looked up some code on the internet which was really hard to find somehow and it was still the same. I just cannot add a layout to my window.
Upvotes: 5
Views: 6466
Reputation: 2238
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 );
}
Now you don't add / set the layout to the MainWindow. You add / set it to the centralWidget.
Upvotes: 19