Search code examples
c++qtqtreeviewqabstractitemmodel

QTreeView: maintaining mapping between QModelIndex and underlying data


I have problems migrating from QTreeWidget to QtreeView. Things that were obvious and trivial with QTreeWidget seem to be impossible with view. Specifically: I have a main window with a treeview in it. TreeView uses the model I've implemented, but not directly – through QSortFilterProxyModel that is set as a tree's model. Now, the user activates an item in the tree and main windows receives a signal itemActivated(QModelIndex item). How can I tell which item of the underlying data was activated? Data is a vector, so with TreeWidget I could just store an item's vector index in the QTreeWidgetItem, but QModelIndex doesn’t even have setData API.


Solution

  • You can define custom roles in your source model, returning the underlying data or an identifier (if there's one) as variant. This has the advantage it works with any number of proxy models in between, as the data will be passed through the models unaltered and now mapping of indexes is required.

    Assuming a model listing contacts, with a value struct/class Contact holding the data. This requires Contact to be registered via Q_DECLARE_METATYPE.

    class ContactModel ... {
        ...
    
        enum Role {
            ContactRole=Qt::UserRole,
            ContactIdRole
        };
    
        QVariant data(...) const {
            ...
            const Contact& contact = ...get from datastructure...
            ...
            switch (role) {
            ...
            case ContactRole:
                 return QVariant::fromValue( contact );
            case ContactIdRole:
                 return contact.id;
            }
        }
        ...
    

    And in the code receiving the index:

    void SomeWidget::indexSelected(const QModelIndex& index)
    {
        const int id = index.data(ContactModel::ContactIdRole).toInt();
        // look up Contact, do something with it
    
        //or:
    
        const Contact contact = index.data(ContactModel::ContactRole).value<Contact>();
        // do something with the contact
    
        ...
    }
    

    The index can be from the contact model itself, or any proxy on top of it - the code here doesn't have to care.