Add widgets to a ScrollArea

Guilherme Nascimento picture Guilherme Nascimento · May 28, 2013 · Viewed 17.7k times · Source

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();

Answer

Shf picture Shf · May 28, 2013

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;