c++qtqt5qgridlayout

How to arrange items in QGridLayout when resizing?


I have a QGridLayout where I add several widgets dynamically, using QGridLayout::addWidget(). I have no problem for these widgets, as they are all the same.

However, I'd like to know how to handle their alignment when I'll resize the widget containing the grid layout. For example, if my widget is wide enough, I could fit 5 widgets on a single row:

------------------------------------------------
| -------  -------  -------  -------  -------  |
| |  1  |  |  2  |  |  3  |  |  4  |  |  5  |  |
| -------  -------  -------  -------  -------  |
|                                              | 

But if I reduce the width of the widget, I'd like to have all the widgets visible, that means creating new row(s):

--------------------
| -------  ------- | 
| |  1  |  |  2  | | 
| -------  ------- | 
| -------  ------- | 
| |  3  |  |  4  | |
| -------  ------- | 
| -------          |
| |  5  |          |
| -------          |
|                  |

I think it can be done via the resize event, but how?


Solution

  • Layouts are used to manage the layout and sizes of a set of widgets. QGridLayout is oriented to handle the widgets inside a static grid, that is to say that the position in column and row of an item does not change reason why it is not possible to create that type of disposition.

    Qt has a great documentation, so it also tells us how to create custom layouts: How to Write A Custom Layout Manager

    The above link shows an example that is precisely what you want: Flow Layout Example