[Interest] 64-bit internal ID for QModelIndex?

Bo Thorsen bo at fioniasoftware.dk
Wed Aug 22 10:04:49 CEST 2012

Den 21-08-2012 20:55, Stephen Chu skrev:
> Is there a way to store a 64-bit internal ID in QModelIndex? The
> function QModelIndex::internalId() returns a 64-bit number but there's
> no way to put one in. The constructor takes only a 32-bit integer.

Hi Stephen,

Please forget all ideas of using the internal pointer. Don't EVER use that!

Instead, create a user role for your model and in the data() method you 
check if this is that role and return your pointer. Something like this 
would do:

class MyModel : public QAbstractListModel {
   enum MyRoles { MyRole = UserRole }

   QVariant data(index, role) {
     if (role == DisplayRole) {
       return mItems[index.row()].first;
     } else if (role == MyUserRole) {
       return mItems[index.row()].second;
     return QVariant();

   QList<QPair<QString, qint64>> mItems;

When you have an index to the model, you can now access your ID with this:


This is written from memory, so you will have to fill in the blanks. And 
you will probably do a more reasonable datatype than a pair with string 
and ID :) But I hope you get the picture.

This is The Right Way(TM) to do *any* kind of extra data role in a model.

I know a lot of people want to use the internal pointer to store stuff 
in, but I will argue any day that if someone uses this, they are doing 
it wrong.

If you have pointers to objects in your model, then store those pointers 
in a QList instead. Yes, it's a few more bytes of memory, but it removes 
so many problems and potential crashes.

If you have a tree model, maybe we can discuss this. But for all flat 
tables and lists, I'm not going to accept any kind of argument for using 
the internal pointer :)

Bo Thorsen,
Fionia Software.


Expert Qt and C++ developer for hire
Contact me if you need expert Qt help

More information about the Interest mailing list