-1

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?

Luca Fülbier
  • 2,641
  • 1
  • 26
  • 43
  • Since `QAbstractItemModel::item` doesn't exist, what do you expect other than implementing it yourself? The `data()` method should be implemented by you, and the code you show in the second line should work as long as the implementation is correct. – Kuba hasn't forgotten Monica Dec 12 '16 at 18:29

1 Answers1

1

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>.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • It has no be noted that Qt::ItemRole doesn't exist either and a substitute has to be added to the model subclass. Qt reserves a couple of integers, so you should choose one that has a value of 256 or higher (for Qt5: http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum). – Luca Fülbier Dec 12 '16 at 18:58
  • @LucaFülbier Should all answers add a disclaimer "Whatever you wrote in your question that's made up, is for you to implement"? I mean, you chose to mix C++ with pseudocode - hopefully you know which is which? – Kuba hasn't forgotten Monica Dec 12 '16 at 19:06
  • Why wouldn't i add additional information for people who might have the same problem? – Luca Fülbier Dec 12 '16 at 19:16