QScrollArea Scrollbar Display Solution

  Pi Ke        2012-03-03 07:48:36       17,029        3    

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.

C++  SOLUTION  GUI  QT  QSCROLLBAR  SCROLLBAR  NOT DISPLAY 

       

  RELATED


  3 COMMENTS


Max [Reply]@ 2012-12-28 17:45:42
Great article! This is exactly what I was looking for. Thanks!
Danny [Reply]@ 2016-11-03 11:46:19

Great piece of code! Just what I needed!

Thank you!

Anonymous [Reply]@ 2017-12-16 06:37:06

Great advice. Thank you.

I did something a little bit different. I used graphic ui designer, placed my buttons manually without using any layout and after that I just wanted to add scrollbars. So for anyone with same problem as me, looking for traditional look without layout auto-scaling buttons etc:

1. select all your randomly placed buttons and other elements and "cut" them with ctrl+x

2. insert scroll area, select main window and press "Lay out in Grid" button ctrl+g

3. insert widget container, select scroll area and press "Lay out in Grid" button ctrl+g

4. set minimumSize of widget container and paste your buttons into it ctrl+v

 



  RANDOM FUN

No functional testing, only unit testing