PDA

View Full Version : Using model indices in complex model item relationships



hackerNovitiate
29th June 2011, 14:30
Given one model index, is it possible to find the model index of another item, if the relationship between the two doesn't match the parent/child structure?

For example, I have the following:


class Person
{
// ...

QString name;
QList<Person*> friends;
}

class PeopleModel : public QAbstractItemModel
{
// ...

QList<Person*> internalData;
}


Assuming that I have the index to a Person (call him Bob), and all his friends are also in the model's internal data, how do I get the index that corresponds to each of Bob's friends?

I know how to find the Person* pointer to each friend, but I can't find a way to map this pointer back into the model. The closest thing I could find was QAbstractItemModel::createIndex(), but that function seems to require knowledge of row+column of every Person. Would I need to record the location of each Person in the model?

Added after 1 35 minutes:

I think I've got it. Based on the TreeItem in http://doc.qt.nokia.com/latest/itemviews-simpletreemodel.html, I can use QList::indexOf() to find the position of the friend-pointer in the model's internal list. If the model was populated systematically, in the same order as the internal list, the pointer's position in the list will correspond to the row number in the model.