Fixed scroll area size with dynamic content layout size

590 Views Asked by At

I want to show a new QWidget, which is set in a QScrollArea that has a grid layout, and then a QVBoxLayout is added to the grid one.

The program allows adding labels dynamically in this QVBoxLayout. I want the scroll area to have a fixed size, and when the labels' size exceeds the scroll area's size (height), the scrollbar should appear (and no changes in the scroll area size).

With my code — adding labels causes the height of the QWidget (window) to increase. The scrollbar can be seen at the beginning, but at some point it disappears, like the QScrollArea is no more there.

QWidget* playlistWindow = new QWidget();
playlistWindow->setAcceptDrops(true);
playlistWindow->resize(200, 300);

QScrollArea* scrollArea = new QScrollArea();
scrollArea->setWidget(playlistWindow);
QVBoxLayout* layout = new QVBoxLayout();
QGridLayout* gridLayout = new QGridLayout();
layout->setAlignment(Qt::AlignTop);
scrollArea->setLayout(gridLayout);
gridLayout->addLayout(layout, 0, 0);
scrollArea->setMaximumHeight(300);

scrollArea->show();   
1

There are 1 best solutions below

0
On

You're setting a layout for the scroll area, and you shouldn't, you just set its widget and let it handle it. The only layout you need is for the QScrollArea::widget. Introducing another layout for the scroll area caused it to not respect the maximum height.

To properly set up a QScrollArea, you need to:

Here's a minimal example demonstrating the above steps:

#include <QApplication>
#include <QScrollArea>
#include <QVBoxLayout>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QScrollArea scrollArea;
    scrollArea.setMaximumHeight(300);
    scrollArea.setWidgetResizable(true);

    QWidget playlistWindow;
    QVBoxLayout layout(&playlistWindow);

    scrollArea.setWidget(&playlistWindow);


    for(int i = 0; i< 20; i++)
        layout.addWidget(new QLabel("label"));

    scrollArea.show();

    return a.exec();
}