QAbstractListModel.match() 导致 QList<T>::operator[] 中的 ASSERT 失败:"index out of range"
QAbstractListModel.match() causes ASSERT failure in QList<T>::operator[]: "index out of range"
我正在使用 QAbstractListModel.match() 搜索项目的索引(如果它存在于模型中)。
QModelIndex childIndex = m_DataSourceModel.match(m_DataSourceModel.index(0,0),Qt::UserRole,QVariant::fromValue(messageID),1,Qt::MatchRecursive)[0];
找不到该项目时,会出现此错误:
ASSERT failure in QList<T>::operator[]: "index out of range", file C:/Qt/5.10.0/mingw53_32/include/QtCore/qlist.h, line 549
手册说:"The list that is returned may be empty." 之后应该用 QModelIndex.isValid()
检查 QModelIndex
那么为什么在我检查索引之前没有匹配项时程序会崩溃?
如文档匹配所示,您可以 return 一个空列表,因此在访问之前您必须验证您至少拥有必要数量的元素:
QModelIndexList indexes = m_DataSourceModel.match(m_DataSourceModel.index(0, 0),
Qt::UserRole,
QVariant::fromValue(messageID),
1,
Qt::MatchRecursive);
if(!indexes.empty()){
QModelIndex childIndex = indexes.first();
// or QModelIndex childIndex = indexes[0];
}
我正在使用 QAbstractListModel.match() 搜索项目的索引(如果它存在于模型中)。
QModelIndex childIndex = m_DataSourceModel.match(m_DataSourceModel.index(0,0),Qt::UserRole,QVariant::fromValue(messageID),1,Qt::MatchRecursive)[0];
找不到该项目时,会出现此错误:
ASSERT failure in QList<T>::operator[]: "index out of range", file C:/Qt/5.10.0/mingw53_32/include/QtCore/qlist.h, line 549
手册说:"The list that is returned may be empty." 之后应该用 QModelIndex.isValid()
检查 QModelIndex那么为什么在我检查索引之前没有匹配项时程序会崩溃?
如文档匹配所示,您可以 return 一个空列表,因此在访问之前您必须验证您至少拥有必要数量的元素:
QModelIndexList indexes = m_DataSourceModel.match(m_DataSourceModel.index(0, 0),
Qt::UserRole,
QVariant::fromValue(messageID),
1,
Qt::MatchRecursive);
if(!indexes.empty()){
QModelIndex childIndex = indexes.first();
// or QModelIndex childIndex = indexes[0];
}