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();
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:
QScrollArea::setWidget
;QScrollArea::setWidgetResizable
, this allows the content to expand beyond the scroll area's size;Here's a minimal example demonstrating the above steps: