How i could make a QScrollArea
stick on the top and grow according to the widgets added to it?
When I add the QScrollArea
to the layout as vlayout->addWidget(scrollArea, 0, Qt::AlignTop);
it doesn’t obey the Qt::AlignTop
flag and is floating on the middle:
class Widget : public QWidget // source: Qt6
{
Q_OBJECT
public:
Widget() : QWidget(nullptr)
{
QVBoxLayout* vlayout = new QVBoxLayout(this);
QScrollArea* scrollArea = new ScrollArea(this);
QWidget* scrollAreaWidget = new QWidget(scrollArea);
QVBoxLayout* scrollAreaLayout = new QVBoxLayout(scrollAreaWidget);
scrollAreaLayout->setContentsMargins(0, 0, 0, 0);
scrollAreaLayout->setSizeConstraint(QLayout::SetFixedSize);
scrollAreaWidget->setLayout(scrollAreaLayout);
scrollArea->setWidget(scrollAreaWidget);
scrollArea->setWidgetResizable(true);
scrollArea->setAlignment(Qt::AlignTop);
scrollArea->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
//scrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
QPushButton* add = new QPushButton("add", this);
connect(add, &QPushButton::clicked, [=]
{
QWidget* widget = new QWidget;
QHBoxLayout* hlayout = new QHBoxLayout(widget);
hlayout->setContentsMargins(0, 0, 0, 0);
QPushButton* button = new QPushButton("button_" + QString::number(scrollAreaLayout->count()), this);
button->setFixedWidth(300);
QPushButton* remove = new QPushButton("remove", this);
hlayout->addWidget(button);
hlayout->addWidget(remove);
connect(remove, &QPushButton::clicked, [=]{ widget->deleteLater(); });
scrollAreaLayout->addWidget(widget, 0, Qt::AlignTop);
});
vlayout->addWidget(add, 0, Qt::AlignTop);
//vlayout->addWidget(scrollArea);
vlayout->addWidget(scrollArea, 0, Qt::AlignTop);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget widget;
widget.show();
}
When i add it to the layout as vlayout->addWidget(scrollArea);
it grows to the entire layout height:
I have tried all size policies scrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
and also:
scrollArea->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
On the documentation it says:
QAbstractScrollArea::AdjustToContents
The scroll area will always adjust to the viewport
Why is it not adjusting? I’m doing something wrong?
What I’m trying to achieve is to have it on the top and make it grow according to the widgets added to it.
It would look like this:
Then it would continue growing for each widget added until there’s no more space on the parent layout, and at this point it would then display the QScrollBars
.
Laila is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.