Reputation: 519
I am using Qt Creator to build a main MainWindow and populate it with all my widgets. I do not set any MainWindow layout in this stage (like "Lay out in a Grid" or "Lay out Horizontally".
When I launch the application I want to dynamically change the MainWindow layout of widgets in it to "Lay out in a Grid" like in Qt Designer by pressing the left button.
I’ve tried hard all possible combinations reading many posts around. The solution in Qt: Can't set layout in QMainWindow doesn't work.
I've tried:
QGridLayout * MainWindowLayout = new QGridLayout;
ui->setupUi(this);
centralWidget()->setLayout(MainWindowLayout);
I've tried to put all my widgets inside a big widget at design time named MainWindowWidget and then setting it as a centralWidget:
QGridLayout * MainWindowLayout = new QGridLayout;
ui->setupUi(this);
setCentralWidget(ui->MainWindowWidget);
centralWidget()->setLayout(MainWindowLayout);
both attempts resulted in the widgets not placed as in a grid as expected.
Here is a code snipped that you can try on an empty application
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
/*
Place some widgets at design time with Creator (at least 2) in the MainWindow form
in a misplaced order and do not apply any "Lay out xxx" right button on QT Creator
*/
ui->setupUi(this);
/* HERE I WANT THE MainWindow or either an Object to take a specific Layout */
QGridLayout * MainWindowLayout = new QGridLayout;
ui->setupUi(this);
centralWidget()->setLayout(MainWindowLayout);
}
Is there any way to change the MainWindow widget's layout like "Lay ouy in a Grid" at design time when using Qt Designer?
Upvotes: -1
Views: 481
Reputation: 519
Finally I got it working doing the following:
I placed all my form widgets into 3 different widgets (QFrames as containers in my case). Then I placed them into the layout as suggested and it worked.
QGridLayout *MainWindowLayout = new QGridLayout();
MainWindowLayout->addWidget(ui->MainFrame, 0, 0); // MainFrame --> My new object containing other widgets
MainWindowLayout->addWidget(ui->DebugButtonsFrame, 0, 1); // DebugButtonsFrame as above
MainWindowLayout->addWidget(ui->DebugMemoFrame, 1, 0); // DebugMemoFrame as above
// Add all other widgets to your layout...
centralWidget()->setLayout(MainWindowLayout);
Upvotes: 0
Reputation: 999
You are creating the layout
But you are not adding widgets
to it. This should fix your issue:
ui->setupUi(this);
QGridLayout *MainWindowLayout = new QGridLayout();
MainWindowLayout->addWidget(ui->label, 0, 0);
MainWindowLayout->addWidget(ui->label_2, 0, 1);
// Add all other widgets to your layout...
centralWidget()->setLayout(MainWindowLayout);
Upvotes: 0