我有一段代码可以做到这一点:一个名为的方法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
which internal callsdelete
时,它确实删除了所有显示的结果。但在那之后,如果我populateWithSearchesults
再次调用,我的应用程序就会崩溃,并且堆栈跟踪会显示这个方法在它崩溃的地方。
我该如何解决这个问题?