(Sounds like a homework question.)
My first approach was to just parent a second widget to the first widget after setting a grid layout. Then you have to get the second widget to resize with the first. I've done that in the past with pop up dialogs in iOS.
@hyde's solution is much more elegant for the problem. I placed everything on the heap, but for such a simple application, everything could be put on the stack instead (QWidget * w = new QWidget();
=> QWidget w;
).
#include <QApplication>
#include <QWidget>
#include <QGridLayout>
#include <QPushButton>
#include <QList>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget * w = new QWidget();
QGridLayout * grid = new QGridLayout();
QList <QPushButton *> buttons;
for(int i = 0; i< 5; i++)
{
buttons.append(new QPushButton("Button "+ QString::number(i+1)));
buttons.last()->setFixedSize(400, 300);
}
grid->addWidget(buttons.at(0),0,0,2,2);// upper left
grid->addWidget(buttons.at(1),0,2,2,2);// upper right
grid->addWidget(buttons.at(2),2,0,2,2);// lower left
grid->addWidget(buttons.at(3),2,2,2,2);// lower right
grid->addWidget(buttons.at(4),1,1,2,2);// centered
w->setLayout(grid);
w->show();
return a.exec();
}
If you want the grid elements to stay centered and not have gaps when you adjust the size of the grid, make sure you add a buffer row/col around the outside, and set the stretch value for them. Like in this example.
Hope that helps.