Robert Robert - 1 year ago 123
C++ Question

How to dynamically add a QScrollArea to a StackedWidget page and add widgets to it?

I'm currently building an application that consists of a

with several pages. The page itself was added in the designer. What I CAN do (in code):

  • add a QVBoxLayout to the page

  • add some custom widgets to it

  • set layout for the page

This works quite well, I can see my widgets appear on the page. These widgets have a fixed height of 25. When there are too many widgets, I can't see all of them. What DOES NOT work is adding a
to the page that allows scrolling up and down, in case there are lots of widgets added to the page.

So here is my code for the situation "as is":

//The header file:

QVBoxLayout *valuesLayout;

//The corresponding .cpp file

valuesLayout = new QVBoxLayout();
valuesPage->setLayout(valuesLayout); //valuesPage is my QStackedWidget page
for (int j=0; j<100; j++)
valuesLayout->addWidget(new PaIndicator(0, "This is a test", 0)); // my custom widgets

How would I have to change/extend the code from above to make my widgets appear in a QScrollArea?

Update: After applying the changes mentioned below I ended up with this:
enter image description here

My now code looks exactly like the lines given in Shf's answer. I have the feeling that I'm getting closer, but something still seems to be wrong here.

Answer Source

You have to set a widget to your scroll area and add the contents to that widget:

QScrollArea *scrollArea = new QScrollArea;
QWidget *scrollWidget = new QWidget;
scrollWidget->setLayout(new QVBoxLayout);
for (int j=0; j<100; j++)
   scrollWidget->layout()->addWidget(new PaIndicator(0, "This is a test", 0));  // my custom widgets

Then add your scroll area to your stacked widget's page:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download