Details
Description
Minimum reproducible example:
#include <QApplication> #include <QDebug> #include <QTreeView> #include <QAbstractListModel> class Model : public QAbstractListModel { Q_OBJECT public: QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { qInfo() << "row:" << index.row() << "column:" << index.column() << "role:" << role; qInfo() << "isValid:" << index.isValid() << "checkIndex:" << checkIndex(index, CheckIndexOption::IndexIsValid); return {}; } int rowCount(const QModelIndex& = {}) const override { return 0; } }; int main(int argc, char** argv) { QApplication app(argc, argv); Model model{}; QTreeView view{}; view.setModel(&model); view.show(); return app.exec(); } #include "main.moc"
If you compile and run it, and then press Ctrl-C in window, it will output following:
row: -1 column: -1 role: 0 qt.core.qabstractitemmodel.checkindex: Index QModelIndex(-1,-1,0x0,QObject(0x0)) is not valid (expected valid) isValid: false checkIndex: false
That's kind of surprising from Qt code, since documentation states that:
Note that it's undefined behavior to pass illegal indices to item models, so applications must refrain from doing so, and not rely on any "defensive" programming that item models could employ to handle illegal indexes gracefully.
Following this advice will result in runtime crash or undefined behaviour if you e.g. access std::vector by QModelIndex::row() in data().
I believe that issue is in following code: https://github.com/qt/qtbase/blob/dev/src/widgets/itemviews/qabstractitemview.cpp#L2367
It should check whether QAbstractItemView::currentIndex() returns valid index and access data only if it does.