【问题标题】:QAbstractListModel.match() causes ASSERT failure in QList<T>::operator[]: "index out of range"QAbstractListModel.match() 导致 QList<T>::operator[] 中的 ASSERT 失败:“索引超出范围”
【发布时间】:2019-04-14 10:26:00
【问题描述】:

我正在使用 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

手册说:“返回的列表可能是空的。”之后应该使用 QModelIndex.isValid() 检查 QModelIndex

那么为什么在我检查索引之前没有匹配项时程序会崩溃?

【问题讨论】:

  • 我如何才能检查它是否有效?我试过 m_DataSourceModel.match(m_DataSourceModel.index(0,0),Qt::UserRole,QVariant::fromValue(messageID),1,Qt::MatchRecursive)[0].isValid();在分配它之前,但它会导致同样的错误
  • 你不必检查它是否有效,但你必须让QModelIndexList不为空。

标签: c++ qt qt5 qlist qmodelindex


【解决方案1】:

如 docs match 所示,您可以返回一个空列表,因此在访问之前您必须确认您至少拥有必要数量的元素:

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];
}

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多