Reputation: 2479
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.
Upvotes: 2
Views: 1531
Reputation: 98425
First, remove the widget from the layout by iterating the layout and removing the item that holds the widget. While doing that you also collect the information about available cells. Then reinsert the widget with proper position and spans.
Upvotes: 2
Reputation: 5968
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);
}
Upvotes: 2
Reputation: 8399
As far as I know, there is no way to do that automatically. I would suggest you to keep a list of the widgets and reposition them by clearing the grid layout and populating it again each time a widget changes its visibility. I found out that only this way I can solve a similar task that I had (for rearranging the widgets in the grid) without creating a custom layout by subclassing QLayout.
Upvotes: 1