我有一段代码可以做到这一点:一个名为prepareUI
的方法使UI能够加载加载到其中的搜索结果。需要清除已经显示的结果时调用的名为onClear
的方法。还有一个名为populateSearchResults
的方法,该方法获取搜索数据并使用它加载UI。保存数据的容器是一个公开可用的指针,因为需要从onClear
中清除结果:
void MyClass::prepareSearchUI() {
//there may be many search results, hence need a scroll view to hold them
fResultsViewBox = new QScrollArea(this);
fResultsViewBox->setGeometry(28,169,224,232);
fSearchResultsLayout = new QGridLayout();
}
void MyClass::onClear() {
//I have tried this, this causes the problem, even though it clears the data correctly
delete fSearchResultContainer;
//tried this, does nothing
QLayoutItem *child;
while ((child = fSearchResultsLayout->takeAt(0)) != 0) {
...
delete child;
}
}
void MyClass::populateWithSearchesults(std::vector<std::string> &aSearchItems) {
fSearchResultContainer = new QWidget();
fSearchResultContainer->setLayout(fSearchResultsLayout);
for (int rowNum = 0; rowNum < aSearchItems.size(); rowNum++) {
QHBoxLayout *row = new QHBoxLayout();
//populate the row with some widgets, all allocated through 'new', without specifying any parent, like
QPushButton *loc = new QPushButton("Foo");
row->addWidget(loc);
fSearchResultsLayout->addLayout(row, rowNum, 0,1,2);
}
fResultsViewBox->setWidget(fSearchResultContainer);
}
问题是,当我调用内部内部称为
onClear
的delete
时,它确实删除了所有显示的结果。但是在那之后,如果我再次调用populateWithSearchesults
,我的应用程序将崩溃,并且堆栈跟踪会将此方法显示为崩溃的位置。我该如何解决这个问题?
最佳答案
您似乎对所有权有一些误解。 QLayout
拥有添加到其中的任何项目的所有权:http://doc.qt.io/qt-5/qlayout.html#addItem
这意味着QLayout
负责删除这些项目。如果删除它们,那么QLayout
还将尝试删除它们,然后您将看到崩溃。QLayout
没有删除内容并重新添加内容的良好功能(例如 removeWidget
可能无法如您所愿。)但这是有原因的。QLayout
不能用作列表 View 。
您想要的是a,等待它, QListView
。它甚至可以为您处理滚动功能,并使添加和删除元素成为可能。