c++ - 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 个小部件,但它只显示最后一个。
解决方案
您只能使用 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);
}
// ...
推荐阅读
- flutter - 使 ListView.builder() 显示下一个(或上一个)元素的一部分
- java - 如何以最有效的方式交换 Java 中的值分配?
- excel - Excel formula that can identify 'mixed' sequences of binomially coded data?
- c++ - 为什么 getline() 后需要按两次 Enter?
- odoo - 如何将 Odoo 更新到主要版本
- java - preserve-order="false" 在测试 NG 中不起作用
- spring - 路径的硬编码以及如何避免它?
- visual-studio-code - 使用 VS Code API 创建和保存具有自定义内容和名称的文件
- mysql - Milvus:在单独的机器上训练和搜索
- python - 计算熊猫数据框中选定列的选定行的平均值,但最终得到一些奇怪的数字