Reputation: 11788
I'm currently building an application that consists of a QStackedWidget
with several pages. The page itself was added in the designer. What I CAN do (in code):
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 QScrollArea
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:
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.
Upvotes: 3
Views: 3716
Reputation: 3493
You would need to add to valuesLayout
only QScrollArea
object, let's say scrollArea
.
You would need to create QWidget
, which would be in scrollArea
, let's say scrollWidget
and set QVBoxLayout
for scrollWidget
, let's say scrollLayout
, now you can add your widgets to scrollLayout
and they would appear inside your QScrollArea
, so the code should look something like this (it's a bit tricky and cofusing, but will be easy in time):
//The header file:
QVBoxLayout *valuesLayout;
QVBoxLayout *scrollLayout;
QScrollArea *scrollArea;
QWidget *scrollWidget;
//The corresponding .cpp file
valuesLayout = new QVBoxLayout(); // creating layout for valuesPage
scrollArea=new QScrollArea(valuesPage); // creates scrollarea, and set valuesPage as it's parent
scrollWidget =new QWidget(scrollArea); // creates scrollwidget, your scrollArea as parent
scrollLayout = new QVBoxLayout(scrollWidget); // creating layout in scrollWidget
for (int j=0; j<100; j++)
{
scrollLayout->addWidget(new PaIndicator(0, "This is a test", 0)); // adding your widgets to scrolllayout
}
scrollArea->setWidget(scrollWidget); // sets scrollArea around scrollWidget
valuesPage->setLayout(valuesLayout); //valuesPage is my QStackedWidget page
valuesLayout->addWidget(scrollArea ); // adding scrollwidget to your mainlayout
Upvotes: 2
Reputation: 12901
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);
scrollArea->setWidget(scrollWidget);
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:
valuesLayout->addWidget(scrollArea);
Upvotes: 4