Qt framework is a popular C++ GUI framework developed by Nokia. And it is also cross platform compatible. Many developers are using Qt to develop C++ GUI programs.
In Qt, some important components are deserved our close attention. Many developers faced the problem when they put some widgets in a QScrollArea widget and they want it to display scroll bars when the widgets inside the QScrollArea overflows. After many experiments, I propose a way which can show scroll bars as you expected.
The relationship between widgets and layout is the key here. Generally, we need not to add layout to scroll area directly. For example, if we want to create a QGridLayout and put many widgets in the GridLayout and then put the QGridLayout in the QScrollArea and if the number of widgets in QGridLayout is too many, then the QScrollArea should show scroll bars accordingly. The correct way to accomplish this should be:
QGridLayout *layout=new QGridLayout;
for(int i=0;i<10;i++){
QWidget* widget=new QWidget;
//widget->setFixedSize(w,h);
layout->addWidget(widget);
}
QScrollArea *scrollArea=new ScrollArea;
QWidget *containerWidget=new QWidget;
containerWidget->setLayout(layout);
scrollArea->setWidgetResizable(true);
scrollArea->setWidget(containerWidget);
In above code snippet, instead of putting the QGridLayout directly into the QScrollArea, we created a container widget called containerWidget and the set its layout to the QGridLayout and then add the containerWidget to the QScrollArea. This solves the problem.
The above code snippet is a simple demo to put widgets in scroll area correctly, sometimes you also need to set the minimum size of the widget in the scroll area in order to show scroll bar correctly.