You can store many types of data into QVariant, like int, string, etc. Also you can store pointers, but only pointers to void (void*).
But what happens when you want to set a property of a object to a instance of class, with setProperty, and after that, you want to retrieve that property? QVariant accepts void*, so you can do something like the following, to store it into QVariant:
QVariant v = qVariantFromValue((void *) yourPointerHere);
and then something like this, in order to retrieve it back from QVariant:
yourPointer = (YourClass *) v.value<void *>();
Having this done each time you have to get the property or set the property is a bit tendentious. We can make this more friendly, using templates:
template <class T> class VPtr
{
public:
static T* asPtr(QVariant v)
{
return (T *) v.value<void *>();
}
static QVariant asQVariant(T* ptr)
{
return qVariantFromValue((void *) ptr);
}
};
So how do you use this? Assuming you have a class MyClass, and you want to store a pointer to this class as a property of a QWidget, or any QObject, or you want to convert it to QVariant, you can do the following:
MyClass *p; QVariant v = VPtr<MyClass>::asQVariant(p); MyClass *p1 = VPtr<MyClass>::asPtr(v);
I think this is more developer friendly than having to write each time those conversion code sequences.
1 Comments.