11

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: enter image description here

3 Answers 3

12

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

    }
2

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.

2

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]);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.