c++qtqscrollarea

How to add multiple widgets to a scroll area


I'm trying to show 10 widgets in a scroll area, but it only shows the last one.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    scroll = ui-> scrollArea;
    scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    scroll->setWidgetResizable(true);
}

void MainWindow::loadproducts(int category){
    ...

    //this is supposed to add widgets to the scroll area

    for(size_t i = 0;i < numberOfWidgets; i++){
        ProductWidget *p = new ProductWidget;
        scroll->setWidget(p);
    }
}

Solution

  • You can only set a widget in the QScrollArea using the setWidget() method, if another one is added it will replace the previous one. If you want to show several widgets then you must place them all within a widget, and that last widget set it in the QScrollArea. For example in your case:

    // ...
    QWidget *container = new QWidget;
    scroll->setWidget(container);
    QVBoxLayout *lay = new QVBoxLayout(container);
    
    for(size_t i=0;i <tempList.size(); i++){
        ProductWidget *p = new ProductWidget(...);
        lay->addWidget(p);
    }
    // ...