Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-106569

Ctrl-C in QTreeView passes invalid QModelIndex to model when model is empty

    XMLWordPrintable

Details

    • 3a0c33da3 (dev), e3ceb846a (6.4), 377abfcb5 (6.5), 615e5dd73 (tqtc/lts-6.2), 409866e03 (tqtc/lts-5.15)

    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.

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            vhilshei Volker Hilsheimer
            equeim Alexey
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: