QVariant: How to extract value into a pointer?
-
One can use
@QVariant::QVariant(int typeId, const void * copy)@
to create a QVariant of specific type with specific value, without knowing the actual definition of the type.
I could not figure out how to do the opposite operation: extract a value to a pointer without knowing the actual definition of the type. I would expect something like
@bool QVariant::value(void *destination, int typeid)@
to exist, which would make a copy of the internal value to an object at pointer destination, assuming that destination points to an object of type typeid, but without knowing the actual definition of that object.
I could only find a template method
@T value()@
which requires to know T.
What would be a way to extract QVariant's value to a memory location of an object based on its type, but without knowing the object definition?
-
Thank you, Sanja, for a quick reply, but this is not what I meant. In your code, the stored value type is void*, which is known type. I need to recover some custom meta type, which is unknown to the piece of code I am in. I only know its custom metatype id.
Here is a work-around code, which I am currently using and which works fine:
@
void *ptr;// let ptr be a pointer to an object with known metatype id, but its definition is not known.
QVariant &v;//created somewhere outside of my code and passed down to me. v encloses an object of meta type id.
const void *src = v.constData();//get a pointer to the internal QVariant data.
QMetaType *mt = new QMetaType(id);//metatype descriptor
mt->construct(ptr,src);//this makes a copy of the object, without knowing what this object actually is.
@
However, I am using here undocumented (but publicly available) method QVariant::constData(), which is not guaranteed to be preserved in the future releases. I would like to use something, that is "officially" approved.Not to mention, that it is a real work-around, which is not as efficient as it could be, if QVariant had a method like value(ptr,id), mentioned above.
Does anyone know how to achieve this in an appropriate way?
-
I am wondering the first statement "const void *src = v.constData();" could be replaced by "v.value<void *>()" ?
-
No, I do not think so, since T in value() must match the type of the data stored in v, which is not void*, but an object of a custom type id.
I will double check it, but my point is that this code is not a proper way of doing it anyway, even though it works. One should also take care of destruction of object at pointer ptr when appropriate, before calling mt->construct, which I do, but such detail is omitted in the above example to demonstrate the essential part only.
-
I have submitted a suggestion on this topic:
https://bugreports.qt-project.org/browse/QTBUG-35466