PDA

View Full Version : Using QVariant with custom data type



QAlex
30th November 2009, 13:22
Hi all,
I read the documentation about QVariant with the little example that I report here:



QVariant v;

MyCustomStruct c;
if (v.canConvert<MyCustomStruct>())
c = v.value<MyCustomStruct>(v);

v = 7;
int i = v.value<int>(); // same as v.toInt()
QString s = v.value<QString>(); // same as v.toString(), s is now "7"
MyCustomStruct c2 = v.value<MyCustomStruct>(); // conversion failed, c2 is empty


From this, I understand that I can initialize a QVariant variable only with data types supported by QVariant itself. Am I right?
Is there a way to initialize the variable v with a custom type?

Thanks for your anwers! ;)
Alex

Lykurg
30th November 2009, 13:27
did you use Q_DECLARE_METATYPE? and obviously an integer can't be converted to your struct...

Eidt: misread your post. The good thing on QVariant is that you don't have to tell, which type it stores. You can check on runtime if it can be converted to one type you need.

As to your question: you can just use Q_DECLARE_METATYPE and you can use your own type with QVariant.

QAlex
30th November 2009, 14:20
Ok! I'll consider using this technique to define my own type.
I think it's the best solution for my porpouses.
I'll try and make you know!

QAlex
4th December 2009, 12:04
Well... I tried and it works!!!
I've created different kind of types and structures to use, but it works always!

Very interesting functionality,
Alex