QAbstractListModel.match() causes ASSERT failure in QList<T>::operator[]: "index out of range"

214 Views Asked by At

I'm searching for the Index of an item(if it's existent in the model) with QAbstractListModel.match().

QModelIndex childIndex = m_DataSourceModel.match(m_DataSourceModel.index(0,0),Qt::UserRole,QVariant::fromValue(messageID),1,Qt::MatchRecursive)[0];

When the item is not found, this error occures:

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 manual says: "The list that is returned may be empty." and afterwards the QModelIndex should be checked with QModelIndex.isValid()

So why is the program crashing when nothing matches before I can check the index?

1

There are 1 best solutions below

0
eyllanesc On BEST ANSWER

As indicated by the docs match, you can return an empty list so before accessing you must verify that you have at least the necessary number of elements:

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