PDA

View Full Version : Cannot cast internal pointer of QModelIndex to custom class pointer



antimatter
22nd May 2015, 14:46
Hello,
I have a QAbstractListModel subclass which has a QList with objects of type "struct Foo". For a custom paint job, I use QStyledItemDelegates for the view. Inside its paint() method, I'd like to handle the real object behind the item directly. So I tried getting it by casting the internal pointer of the model index. This will compile, but only yield 0.


Foo *f = static_cast<Foo*>(index.internalPointer());

The problem here is, that the internal pointer is already 0. In the past I successfully used static casts on internal pointers.

On the other hand, using the model from the index and a custom method in the model works quite well. Yet, this solution looks rather long-winded.


Foo *f = ((FooModel*)index.model()).fooByIndex(index);

// Model definiton (excerpt)
class FooModel : public QAbstractListModel
{
public:
Foo *fooByIndex(const QModelIndex &index);
}


Am I missing something here or is the internal pointer supposed to be null?


Andreas

wysota
22nd May 2015, 20:38
I would guess the index you are calling the function on is already invalid.

ChrisW67
22nd May 2015, 20:55
Or you never put a Foo* in the QModelIndex through your createIndex() calls.

anda_skoa
23rd May 2015, 13:57
So I tried getting it by casting the internal pointer of the model index.
That is very bad in any way, it is called "internal" for a reason. Only the model should ever make assumption about it because it is the one creating the index.

I would recommend adding a role that returns the full model data entry



Foo foo = index.data(FooRole).value<Foo>();


Cheers,
_