Search code examples
qtmodel-view

Retrieving original item from QAbstractItemModel subclass


I need to implement a QAbstractListModel subclass so i can use a QListView with a domain class of our project.

The documentation covers nicely what methods i have to provide, but what baffles me is that there is no obvious way to retrieve the original object for a specific QModelIndex.

What i am looking for is something like this:

model MyModel<MyDomainEntity>(listOfDomainEntities);
model.item(someIndexComputedFromSelection); // Should return a MyDomainEntity

or

MyDomainEntity ent = model.data(someIndexComputedFromSelection, Qt::ItemRole)
                          .value<MyDomainEntity>();

But i can't find any easy way to do that, besides implementing these model methods myself. Am i missing something?


Solution

  • You have to plug the MyDomainEntity into the QMetaType system. This will automatically make QVariant support it as well. And that's all you need for the code in your question to work.

    All you need is:

    // Interface
    struct MyDomainEntity {
       int a;
    };
    Q_DECLARE_METATYPE(MyDomainEntity)
    
    int main() {
       QVariant f;
       f.setValue(MyDomainEntity{3});
       Q_ASSERT(f.value<MyDomainEntity>().a == 3);
    }
    

    It also makes QVariant able to carry Qt containers of your type, e.g. QList<MyDomainEntity>.