Add widgets to a ScrollArea
Asked Answered
P

1

6

I am creating a window dimanica to the downloads list. But the scrollbar does not work and the "widgets children" are "cut".

Where can I be wrong? Thanks.

Source:

    QWidget *central = new QWidget;
    QScrollArea *scroll = new QScrollArea;
    QVBoxLayout *layout = new QVBoxLayout(scroll);
    scroll->setWidget(central);
    scroll->setWidgetResizable(true);

    int i=0;
    while(i<10){
        QWidget *p1 = new QWidget;
        QHBoxLayout *hl = new QHBoxLayout(p1);
        QLabel *label1 = new QLabel("test");
        QLabel *label2 = new QLabel("0%");
        hl->addWidget(label1);
        hl->addWidget(label2);
        layout->addWidget(p1);
        i++;
    }

    QMainWindow *w = new QMainWindow;
    w->setGeometry(50,50,480,320);
    w->setCentralWidget(scroll);
    w->show();
Portis answered 28/5, 2013 at 15:10 Comment(0)
F
10

Found your mistake, you should set layout to widget central not to scroll:

QWidget *central = new QWidget;
QScrollArea *scroll = new QScrollArea;
QVBoxLayout *layout = new QVBoxLayout(central);
scroll->setWidget(central);
scroll->setWidgetResizable(true);

EDITED:

Your labels already take all available space, if you noticed, label1 begins at left border ends in the middle, where label2 starts and ends at the right border. If I understood you correctly, you want label1 to take all the space available, while label2 with percents to take only what space is needed, no more?

Read about QSizePolicy class and use setSizePolicy() on your labels. Try to insert this line right after label2 declaration:

QLabel *label2 = new QLabel("0%");
label2->setSizePolicy(QSizePolicy::QSizePolicy::Maximum,QSizePolicy::Maximum);

And add line layout->addStretch(); right before QMainWindow *w = new QMainWindow;

Foyer answered 28/5, 2013 at 19:10 Comment(6)
Nice, But has the only stretch to Horizontal?Portis
you want to keep geometry (50,50,480,320) and stretch labels take all horizontal space?Foyer
Yes, I want each item (Widget child) occupy all space horizontally (horizontal only). Could you help me? Thank you for your attention. No need to be fixed height or width. The window can be resized.Portis
i don't understant, what you want to achive, in my test app, all works perfectly. Why don't you post screenshot with your current situation, and how you want to change itFoyer
Maybe if you replace while(i<10) by while(i<3) you will see the problem. Screenshot: i.sstatic.net/CRVhq.pngPortis
add line layout->addStretch(); before QMainWindow *w = new QMainWindow;Foyer

© 2022 - 2024 — McMap. All rights reserved.