PDA

View Full Version : Search QTableView with a value(e.g. "ID") which is not shown in the table



sami1592
8th February 2016, 09:32
Scenario:
Say, I have a person class

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

The list of Person class is maintained in class called MyAllData class which is outside of my model class

The model class I am using; inherits QAbstractTableModel

MyCustomModelClass : QAbstractTableModel

MyCustomModelClass has a reference to the person list. 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?

anda_skoa
8th February 2016, 10:23
Two options:

1) Add ID as a column in the model but hide it in the view, then use QAbstractItemModel::match for searching

2) Implement a search function in your model that gets and ID value and returns the QModelIndex for the respective row

Cheers,
_

sami1592
8th February 2016, 12:03
2) Implement a search function in your model that gets and ID value and returns the QModelIndex for the respective row
_

I understood Option 1.
Unfortunately I did not understand Option 2 :(

anda_skoa
8th February 2016, 12:22
For option 2 you would add a method for getting an index of the model for a given ID.

You could do that outside the model but it is probably more convenient to put it into the model class.

Something like



QModelIndex MyCustomModelClass::indexForID(int id) const
{
for (int i = 0; i < data.count(); ++i) {
if (data.at(i).id == id) {
return index(i, 0);
}
}

return QModelIndex();
}

I.e. find the row the person with the given ID is in, return the model index for that row.
"data" is your reference to the MyAllData object, assuming that it can be queried for number of entries and can be asked for a specific entry.

You could also have a findById function in the data class and then use its return value to create the index, etc.

Cheers,
_