0

Scenario:

Say, I have a person class

class Person{
    int id;          // only unique value, NOT displayed
    QString name;    // displayed
    QString address; // displayed 
    QString age;     // displayed
    etc etc          // displayed
}

The model class I am using; inherits QAbstractTableModel - MyCustomModelClass : QAbstractTableModel . MyCustomModelClass has a reference to the person list. Person list is maintained in class called MyAllData which is outside of my model class.

The table does not display the ID number of a person. But it is the only thing with which one can identify a person separately. If I want to search my table data with ID then how can I do that?

Yousuf Azad
  • 414
  • 1
  • 7
  • 17

1 Answers1

1

It depends a bit on which method you would like to search your model class with. Usually, I would implement a Qt::UserRole in your data() method. This role could either return your ID only or a pointer to your complete structure (using Q_DECLARE_METATYPE).

Then, you can either work your way through the model indices on your own, calling

model->data(idx, Qt::UserRole).toValue<Person*>()

or use methods like QT's match(.) and use Qt::UserRole there.

A third possibility would be to return the ID as if you would like to display it, but hiding the column in your view.

IceFire
  • 4,016
  • 2
  • 31
  • 51
  • I think your answer will work! I will post my updates :D One question though, what did you mean by this? `(using Q_DECLARE_METATYPE).` Why would I need this to save a pointer? Can you explain a little more? – Yousuf Azad Feb 08 '16 at 09:07
  • 1
    Yes, of course. data() returns QVariant, so if you want to return a pointer to Person*, you need to tell QT that it has to accept Person* as a meta type. So, you can just write Q_DECLARE_METATYPE(Person*) below the definition of Person, which will tell QT. Afterwards, in data you can write: QVariant result; result.setValue(...); You may use a pointer since the data seems to be stored anyways somewhere, so a pointer to the data is a good idea. If this works fine depends a lot on how and where your data is stored. If you are merely interested in the ID, you might just return it. – IceFire Feb 08 '16 at 09:16