tags:

views:

37

answers:

2

I store objects of a custom data type in QStandardListItems. I recover these objects by calling:

i.data(Qt::UserRole + 1).value<LiteReach>();

This only creates a new object in the stack. Any changes I do to them would be temporary.

Is there a way to get the base object stored in itemData so that it could be manipulated directly? If not what would be the preferred method to change itemData?

I would like not to call setData each time an object is modified since it would consume a lot of resources.

+1  A: 

You could use pointers that allow access to the concrete data objects instead of copying the whole data into a QVariant like above.

The problem is that value() returns a copy of your data. So if you make any modifications, they will be gone as soon as the copy is removed from stack.

If you don't want to use pointers, I guess you'll have to stick with setData().

BastiBense
How can I set the (LiteNode*) type as a meta type? I tried Q_DECLARE_METATYPE(LiteNode*) but it doesn't seem to work.
Gayan
You probably forgot to `#include <QMetaType>` in your header for that class.
BastiBense
Q_DECLARE_METATYPE(LiteNode*) worked. Thanks. I opted to derive my class from QStandardItem so the whole issue would not come up again.
Gayan
A: 

I was under the impression that the QVariant class was not intended for pointer storage.

However, if you really want to do it, you could always do something like

LiteNode* myPtr = new LiteNode;
QVariant v(reinterpret_cast<quint32>(myPtr)); //or quint64 for 64-bit apps
myPtr = reinterpret_cast<LiteNode*>(v.value<quint32>());

That way you don't even have to declare your object type as a Qt Metatype.

badgerr
And *if* you do this, I suggest to use `quintptr` instead of `quint32`. Because pointers on 64-bit systems would get messed up badly if you stored them in a 32-bit integer. ;)
BastiBense
The bitness was one of the reasons that I didn't opt for this approach. Though this seemed like a limitation at the time (I come from MFC origins) I think the inheritance model is a lot more elegant than using itemData.
Gayan