c++qtlayoutwidgetflowlayout

Qt Auto-arrange widgets in layout


I'm new to Qt and have a problem that I haven't been able to solve.

What I have is a scroll area that I add widgets to (what the widgets are doesn't matter). Each of the widgets has a static size and they all have the same width (this might be important). What I'm trying to do is to have a layout/setup such that all these widgets are displayed on the scroll area horizontally until there is not enough room for another widget, at which point it starts putting the widgets on a new row, continuing until there are none left.

I've thought about ways to implement this manually, but I feel like this is something that Qt already supports and I just haven't been able to find the documentation on it.


Solution

  • You can see the Flow Layout Example. It demonstrates a custom layout that arranges child widgets from left to right and top to bottom. The items are first laid out horizontally and then vertically when each line in the layout runs out of space.

    The FlowLayout class inherits QLayout. It is a custom layout class that arranges its child widgets horizontally and vertically. You can implement it as shown in the link and create a custom widget that holds the flow-layout and set that as the QScrollArea’s widget.

    scrollArea->setWidgetResizable(true); // Important or else the widget won't expand to the size of the QScrollArea, resulting in the FlowLayout showing up as a vertical list of items rather than a flow layout
    scrollArea->setWidget(new CustomWidget);
    

    In the constructor of CustomWidget :

    // Create FlowLayout
    FlowLayout *flowLayout = new FlowLayout;
    
    // Populate FlowLayout with your widgets
    for (int i=0; i<n; i++) 
    {
        ...
        flowLayout->addWidget(widget);
    }
    
    setLayout(flowLayout);