Understanding Qt view-model architecture: when to create and how to delete indexes in QAbstractItemModel implementation?

  • I'm currently migrating my project from QTreeWidget to QtreeView, and have a lot of problems caused by poor understanding of the Qt model-view design. So far I couldn't find answers even in Qt examples.

    I've implemented my QAbstractItemModel. I'm returning strings to be viewed in the QTreeView through data method. Now, the underlying data will change in runtime. To handle this my model is subscribed to a notification that does emit dataChanged(index(0,0), index(rowCount() - 1, LastColumn));. The question is: how to create and delete QModelIndex objects? One of the Qt examples reimplements index method, so I did the same:
    @QModelIndex CFileListModel::index(int row, int column, const QModelIndex &/parent/) const
    QModelIndex index = createIndex(row, column);
    return index;

    However, data is static in that example and in my case it changes at runtime. Is my index implemetation correct? What if index is called more than once for the same coordinates? Do I need to somehow delete old indexes before emitting dataChanged?

  • Moderators


    If your model only returns strings, it's much easier to work with QStandardItemModel than QAbstractItemModel. It takes care lots of the details for you, so you don't even have to reimplement anything. Just call setItem() or setData() at runtime and your QTreeView will update itself -- you don't have to create indexes manually.

  • Hmm. My model returns strings and icons for Qt::DecorationRole. Can QStandardItemModel handle icons?

  • Moderators

    Yes. QStandardItem has a constructor that accepts an QIcon: http://qt-project.org/doc/qt-5.1/qtgui/qstandarditem.html#QStandardItem-3

    Or, call QStandardItem::setIcon()

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.