Search code examples
qtqt5qlayout

Size constraints for Qt layouts


My widget has two layouts. The main layout is outerLayout, and it should always occupy the entire widget. This contains a QLabel and a second layout named innerLayout.

innerLayout should be centered inside outerLayout and it should only be large enough to contain its widgets. I've set size constraints for both layouts, but in the following code, innerLayout expands to fill outerLayout.

outerLayout = new QVBoxLayout();
outerLayout->addWidget(label);
outerLayout->setSizeConstraint(QLayout::SetMaximumSize);
innerLayout = new QGridLayout();
innerLayout->setAlignment(Qt::AlignHCenter);
innerLayout->setSizeConstraint(QLayout::SetFixedSize);
outerLayout ->addLayout(innerLayout);
setLayout(outerLayout);

If I set the size constraint for both layouts to SetFixedSize, both layouts will be reduced to their minimum size. But I want the outer layout to occupy the entire space and the inner layout to use the minimum possible space. Any ideas?


Solution

  • Use spacers as extra widgets of outerlayout. In other words: the spacers will be siblings of innerlayout and will push inner layout to it's minimal needed surface. You will need horizontal and vertical spacers.