0

I got the following arrangement (original here):

test_image

Five unconvencional unsual sized buttons (w:400, h:300) and they are arranged int the following way: four square mode (two on top and two at buttom), closely tight together, and a fifth button in the center, overlaping the instersection of the other four buttons. I would like to know if is there any layout (gridlayout, form layout, etc) that I can use to keep this arrangement when I expand, maximize and/or minimize the window? Thanks for any help.

hyde
  • 60,639
  • 21
  • 115
  • 176

2 Answers2

0

Use QGridLayout, with size 4x4. Then make each button use 2x2 grid layout cells, which you can use by using the right QGridLayout::addWidget() overload. There give columnSpan and rowSpan of 2.

hyde
  • 60,639
  • 21
  • 115
  • 176
0

(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.

Community
  • 1
  • 1
phyatt
  • 18,472
  • 5
  • 61
  • 80