首页 > 解决方案 > C++ Qt如何在滚动区域添加小部件?

问题描述

我试图在滚动区域中显示自定义小部件,但它只显示最后一个。

滚动区域的内容必须随着组合框索引而动态变化,它们也会改变并显示最后一个元素。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    fileMenu = ui->menuBar->addMenu(tr("&Archivo"));
    openFileAction = new QAction(tr("Abir archivo"), this);
    connect(openFileAction,
            SIGNAL(triggered()),
            this,
            SLOT(openFile()));
    fileMenu->addAction(openFileAction);


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


    ui->stackedWidget->setCurrentIndex(0);
}

vector<product> MainWindow::filter(QString cad)
{
    vector <product> tempList;
    QMessageBox message;
    for(size_t i(0);i<products.size();i++){
        if(products.at(i).getId().contains(cad)){
            product *p = new product;
            p->setId(products.at(i).getId());
            p->setName(products.at(i).getName());
            p->setPrice(products.at(i).getPrice());
            tempList.push_back(*p);
        }
    }
    return tempList;
}

void MainWindow::loadproducts(int category){
    QMessageBox message;
    vector <product> tempList;
    switch(category){

    case Alimentos:{
        tempList=filter("AB");
        break;
        }

    case Libros:{
        tempList=filter("L");
        break;
        }

    case Electronicos:{
        tempList=filter("E");
        break;
        }

    case Hogar:{
        tempList=filter("HC");
        break;
        }

    case Deporte:{
        tempList=filter("D");
        break;
        }

    case Todos:{
        tempList=products;
        break;
        }

    default:{
        break;
        }
    }

//THIS FOR IS SUPPOSED TO ADD WIDGETS TO SCROLL AREA

    for(size_t i=0;i<tempList.size();i++){
        ProductWidget *p = new ProductWidget(widget, tempList.at(i).getId(), tempList.at(i).getName(), tempList.at(i).getPrice());
        scroll->setWidget(p);
    }

    tempList.clear();
}

滚动区域必须显示 10 个小部件,但它只显示最后一个。

标签: c++qt

解决方案


您只能使用 setWidget() 方法在 QScrollArea 中设置一个小部件,如果添加另一个小部件,它将替换前一个。如果要显示多个小部件,则必须将它们全部放在一个小部件中,最后一个小部件将其设置在 QScrollArea 中。例如在你的情况下:

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

推荐阅读