PDA

View Full Version : QModelIndex::parent question



QPlace
25th June 2009, 21:16
It is my first attempt to get a tree model going and I am stuck - don't quite understand how to implement method:

QModelIndex QAbstractItemModel::parent ( const QModelIndex& index ) const

My model displays QList<Apartments> as root items, where each apartment has one or more occupants. When I construct an index, reimplementing method

QModelIndex QAbstractItemModel::index(int row, int column, const QModelIndex &parent) const

I construct the index with createIndex(row, column, Pointer), where Pointer is a pointer to either Apartment or Occupant. I know what to use, Apartment or Occupant, depending on parent.isValid() call.

My question is: when I have to construct parent for a given index in the QAbstractItemModel::parent - how do I know if I am getting a root item (Apartment) to which I have to return QModelIndex() or a child Item (Occupant) to which I have to construct a parent?

Any help is greatly appreciated

wysota
25th June 2009, 23:07
Derive both Apartment and Occupant from the common base class and either use dynamic_cast or implement virtual methods isOccupant() and isApartment() in the base class and reimplement them in the subclasses properly so that you can determine the type of the object by calling one of these.

QPlace
26th June 2009, 02:28
I was afraid that would be the answer, hoping that I missed something in the documentation. :(

So, one has to rely on RTTI to construct a model for a tree view.. Sad.

I have another, kind of a follow-up question.

I am under the assumption (did not actually test it myself) that all view models are "virtual", in a sense that the Qt framework will not ask model for a complete range of QModelIndexes.

Suppose I have 10^6 Occupants in the city and my QTreeView has only two visible Apartments with 5 occupants total. Will my model be a subject to 10^6 or more calls to ::index and :: parent methods? If yes - what is the Qt-way to implement virtual models?

wysota
26th June 2009, 09:45
So, one has to rely on RTTI to construct a model for a tree view.. Sad.
Not really. But with your current design you have to either use RTTI or virtual methods.


I am under the assumption (did not actually test it myself) that all view models are "virtual", in a sense that the Qt framework will not ask model for a complete range of QModelIndexes.

Suppose I have 10^6 Occupants in the city and my QTreeView has only two visible Apartments with 5 occupants total. Will my model be a subject to 10^6 or more calls to ::index and :: parent methods? If yes - what is the Qt-way to implement virtual models?

The view will only ask for the indexes it currently needs. Just remember it might need them all if you, for example, force the width of a column to be resized to the size of its contents.

QPlace
26th June 2009, 13:26
Thank you for the help and clarifications.