我一直在寻找解决这个问题的方法,我开始相信这可能是 Qt 函数本身的一个错误。问题是,在您调用 QItemSelectionModel::selectedIndexes() 后,当程序尝试破坏此函数返回的 QModelIndexList 时,程序将崩溃。在崩溃之前,您会收到以下调试消息:
调试断言失败!
(...)
文件:f:\dd\vctools\crt_bld\self_x86\crt\src\dbgheap.c
行:1419
表达式:_pFirstBlock == pHead
(...)
下面是最简单的会导致问题的代码,大家可以自己测试一下:
#include <QApplication>
#include <QStringList>
#include <QStringListModel>
#include <QItemSelectionModel>
#include <QModelIndex>
#include <QModelIndexList>
#include <QListView>
#include <QItemSelectionModel>
void doSomethingWithSelection(QItemSelectionModel* selectionmodel);
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QStringList list;
list.push_back("1");
list.push_back("2");
list.push_back("3");
list.push_back("4");
QStringListModel model(list);
QListView view;
view.setModel(&model);
view.setSelectionMode(QAbstractItemView::ExtendedSelection);
QItemSelectionModel *selectionmodel = view.selectionModel();
QModelIndex first = model.index(0);
QModelIndex last = model.index(2);
QItemSelection selection(first, last);
selectionmodel->select(selection,QItemSelectionModel::Select);
doSomethingWithSelection(selectionmodel);
view.show();
return a.exec();
}
void doSomethingWithSelection(QItemSelectionModel* selectionmodel)
{
QModelIndexList indexlist = selectionmodel->selectedIndexes();
// this is what causes the error. I put this inside a function
// so the error will happen when exiting the function,
// when the program try to destroy the list nodes.
}