[Qt-interest] QModelIndex problems to represent a given data structure

Andre Somers andre at familiesomers.nl
Mon Jul 5 18:06:35 CEST 2010


On 5-7-2010 17:39, Justus Best wrote:
>    Hi,
>
> I have some problems to display a hierarchic data structure with the Qt
> Model/View concept.
>
> The main problem is that it is not possible to identify which type the
> internal-pointer has. If I could use the internal-pointer in combination
> with the internal-id it would be easy to cast to the right type.
>
> Btw. it's not clear to me why the create-index function in
> QAbstractItemModel takes an quin32 as id parameter and the QModelIndex
> returns a qint64 as internal-id.
>
> Hope it gets clear what my Problem is. I'm at the moment thinking of
> some possible Solutions,
>
> 1. Overwriting the createIndex() function to create an index with
> pointer and Id.
>    
Won't work.
> 2. Subclassing QModelIndex to add type safety
>    
Not going to work either, since the Qt functions returning a QModelIndex 
will return the default one, not yours.
> 3. Mirroring the given data structure into a lightweight private data
> structure which only keeps references to the given data structure which
> can always be casted into the same type, like the example in the qt docs.
>    
Basically, that is how to do it. But it depends on your own data structure.
> 4.throwing away the qt model view concept and writing my own tree based
> display widget.
>    
Sounds a bit too radical.

One basic thing to remember when using Qt's model/view framework: use 
them as an *interface* to your own data structures, not as a replacement 
of them! This is an important thing to keep in mind. How to use the 
internal id depends on your own data structure. Also remember, that you 
still have the row and the column number to work with; the internal 
id/internal pointer is just an extra piece of information you can put in 
the QModelIndex to make the mapping easier.

I also never quite understood why different types were used for the 
internal id in QModelIndex::internalId and 
QAbstractItemModel::createIndex, but there it is. You can not use them 
both at the same time either; it is a union if I'm correct.

What I have done in the past, is to create a small struct that contains 
the pointers and type information to the actual data, and point to those 
either via the internalPointer or storing them in a list and using the 
internalId.
Perhaps also possible, depending on the size of your data structure, is 
to pack more information in the quint32 id than just one number. You can 
use some of the bits of the id to store the type. Some ANDs, ORs and bit 
shifting will make that work. You just need to be sure that the id part 
of the id stays within range.

André

-- 
Nokia Certified Qt Developer.
Interested in Qt related job offers or freelance Qt consulting work.




More information about the Qt-interest-old mailing list