0

My question refers to:

How to verify QVariant of type QVariant::UserType is expected type?

Specifically, if

struct MyType {
  ....
};

Q_DECLARE_METATYPE(MyType);

QVariant v(QVariant::fromValue(MyType());

Is there a way to find out what v.userType() will return at compile-time?

Community
  • 1
  • 1
user1095108
  • 14,119
  • 9
  • 58
  • 116

2 Answers2

3

There is no way to find this out at compile time, because it's not determined until runtime. You can get it with qMetaTypeId<MyType>().

Dan Milburn
  • 5,600
  • 1
  • 25
  • 18
1

From what I've tried, the indexes for userType() that are declared by you will start at 256, and then increase by one.

So if you use Q_DECLARE_METATYPE(someType);, this type will then be returning 256 on userType() calls. If you then do Q_DECLARE_METATYPE(someOtherType);, it will be returning 257 and so on.

Also, if you need to check it in the run-time, you can get the value once, and then use it for comparations:

int MyTypeID = QVariant::fromValue(MyType()).userType(); 
if( someObject.userType == MyTypeID )
{
//do stuff
}

You might also want to look at qRegisterMetaType() function.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105