Change resize behavior in Qt layouts


I want my custom widgets to gain extra space when the dialog is resized. This was working when I only had a handful of widgets, but after adding several more columns of these same widgets and putting them in a QGridLayout, the extra space merely goes in as padding between the widgets.

8/26/2009 6:13:54 PM

Accepted Answer

I've had trouble with this in the past and here are some of the things I've found:

  1. First make sure all the widgets you want to expand have sizePolicy set to "Expanding".

  2. Make sure the widgets that make up your custom widgets are in a layout that allows for expanding. You can check this by just adding one of your custom widgets to the window and seeing that it expands as expected.

  3. Make sure any widgets on the form that you do not want to expand have a fixed (minimum=maximum) size in the dimension you want them to stay static.

  4. Sometimes the grid layout causes some weird spacing issues because rows are resized based on the largest widget in the entire row and similarly for columns. For some layouts, it is better to use a vertical layout that contains horizontal layouts or vica versa to create a grid-like effect. Only this way, each sub-layout is spaced independently of the other rows or columns.

8/26/2009 8:50:32 PM

Controlling grid expansion programatically

I've found that you can easily control which columns/rows expand and which columns/rows stay fixed in width by using QGridLayout::setColumnStretch() and QGridLayout::setRowStretch(). You'll need to provide weights to the specific columns (0 for no stretch).

For example, if you want column 0 to not take up any room and column 1 to take the rest of the window's room, do this:

QGridLayout* layout ;
// Set up the layout
layout->setColumnStretch( 0, 0 ) ; // Give column 0 no stretch ability
layout->setColumnStretch( 1, 1 ) ; // Give column 1 stretch ability of ratio 1

Controlling grid expansion using Qt Designer

You can do what I described above if you're using Designer. Just look for the widget properties layoutRowStretch and layoutColumnStretch. It'll contain a comma-separated list of integers.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow