简体   繁体   中英

Which Qt Widget to scroll through widgets?

I am currently working on a Qt project for my school. For this project I need to list an unknown number of elements in a window without resizing its content.

I've used some VBoxLayout in the past, but it isn't what I am searching at all. This widget resizes its content depending on the number of elements it contains. What I would like is to add as much widgets as I need into the "scrolling widget", which will stack next to each other automatically and won't resize.

I tried using QScrollArea but I wasn't able to make elements stack on each others.

Here is a small drawing explaining my problem: 在此输入图像描述

Here is how I do it with a QVBoxLayout and a QScrollArea :

//scrollview so all items fit in window
    QScrollArea* techScroll = new QScrollArea(tabWidget);
    techScroll->setBackgroundRole(QPalette::Window);
    techScroll->setFrameShadow(QFrame::Plain);
    techScroll->setFrameShape(QFrame::NoFrame);
    techScroll->setWidgetResizable(true);

    //vertical box that contains all the checkboxes for the filters 
    QWidget* techArea = new QWidget(tabWidget);
    techArea->setObjectName("techarea");
    techArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
    techArea->setLayout(new QVBoxLayout(techArea));
    techScroll->setWidget(techArea);

Then when adding items you do it like this (with lay = techArea->layout() and parent = techarea :

for(std::set<Event::Enum>::iterator it = validEvents.begin(); it != validEvents.end();
    ++it){
        QCheckBox* chk = new QCheckBox(
        "text", parent);

        if(lay){
            lay->addWidget(chk);
        }   

    }

RedX's answer was a bit vague, but I got his method to work:

QRadioButton *radio[40];

for (int i = 0;i<40;i++)
    radio[i] = new QRadioButton(tr("&Radio button 1"));

QWidget* techArea = new QWidget;
techArea->setObjectName("techarea");
techArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
techArea->setLayout(new QVBoxLayout(techArea));
ui->scrollArea->setWidget(techArea);

QLayout *lay = techArea->layout();

for (int i = 0;i<40;i++)
    lay->addWidget(radio[i]);

If your display elements are simple, the easiest solution is a QListWidget . This will automatically resize itself and inform the QScrollArea when you add items. You just have to call myScrollAlrea -> setWidget (myListWidget) to initialise, and then myListWidget -> addItem (myListWidgetItem) to add new items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM