3

Is there anyway to create a QVariant from a metatype id ?

For example :

int id = qRegisterMetaType<MyStruct>();
QVariant myVariant = QVariant::fromMetaType(id);

So myVariant is now a QVariant containing a default-constructed value of "MyStruct".

I didn't find anyway to do this with the QVariant API, did I miss something, or is there any trick ?

Thanks

Aurelien
  • 1,032
  • 2
  • 10
  • 24

2 Answers2

4

One of the QVariant constructors does it:

QVariant::QVariant(int typeId, const void *copy)

Note that copy can be a nullptr. So, your code would be:

auto id = qRegisterMetaType<MyStruct>();
QVariant myVariant{id, nullptr};

Of course, if you have the type itself available, there's no point to using the metatype id, you should be using fromValue.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • Thanks, I was looking for it. I have the metatype id available, but not the type itself in this piece of code. – Aurelien Jun 25 '16 at 07:53
1

Here is example how to do it:

Instead of QVariant myVariant = QVariant::fromMetaType(id); you can write:

MyStruct s;
QVariant var;
var.setValue(s);

Another option is fromValue (found here):

MyCustomStruct s;
QVariant var = QVariant::fromValue(s);
mvidelgauz
  • 2,176
  • 1
  • 16
  • 23