Search code examples
c++qtqgridlayout

QGridLayout 3x3 grid resize widgets


I have 9 QWidgets. Sometimes they are invisible. They are all in a 3x3 grid.

[0][3][6]
[1][4][7]
[2][5][8]

Now if for example widget 3 is made invisible, other widgets should should resize:

[   0   ][   6   ]
[  1 ][  4 ][  7 ]
[  2 ][  5 ][  8 ]

The same should happen vertically, basically all the empty space should be filled but I'm not sure how to do that. When I set a widget invisible, the empty space is not taken.

QGroupBox *parent = getParent();
QGridLayout *layout = new QGridLayout;
layout->setMargin(0);
layout->setMargin(5);
int w = parent->geometry().width();
int h = parent->geometry().height();
QSize min(w/3-2*layout->spacing(),h/3-2*layout->spacing());
QSize max(w,h);
for (int n = 0; n < 6; ++n)
{
    layout->setRowStretch(n,6);
    layout->setColumnStretch(n,6);
}

for (size_t n = 0, t = widgets.size(); n < t; ++n)
{
    QWidget *widget = widgets[n];
    widget->setMinimumSize(min);
    widget->setMaximumSize(max);
    widget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    layout->addWidget(widget);
}

Thanks in advance for the help.


Solution

  • I have the similar experience. I used such widget to visualize dynamically changed configuration of device.

    The required behavior can be achieved by using QVBoxLayout as row and QWidget ad cell (column). In my case I used custom widget derived from QLabel as cell. Everything works from the box without tuning of geometry.

    Pseudo code:

    // Inside widget's constructor (or createLayout function).
    topLayout = new QVBoxLayout ();
    
    aLayout = new QHBoxLayout ();
    bLayout = new QHBoxLayout ();
    cLayout = new QHBoxLayout ();
    
    topLayout->addLayout (aLayout);
    topLayout->addLayout (bLayout);
    topLayout->addLayout (cLayout);
    
    setLayout (topLayout);
    
    ...
    
    // Add cell to corresponding row.
    void add_cell (QWidget * cell)
    {
        aLayout->addWidget (cell);
    }