How to check QVariant type of QVariant :: UserType type?

I am writing test code that automatically iterates over all Q_PROPERTY widgets, and some properties use types registered through qRegisterMetaType. If I want to read / write them to QVariant, I need to use QVariant :: UserType when saving them in the variant. So far so good.

But when I want to test the reading and writing of these properties, I also need to know their type. For things that are already standard qt types, I can do this with QVariant :: type (), but since I have many types of users, how will this be done?

From the QVariant api, I noticed this:

bool QVariant::canConvert ( Type t ) const

But I slightly doubt that this will lead to the wrong types in case of enums?

So, what would be a reliable way to check which type of user type is stored in QVariant?

+6
qt qvariant
source share
1 answer

For custom types, QVariant :: userType () . It works like QVariant :: type (), but returns an integer of type identifiers of a user-defined type, while QVariant :: type () always returns QVariant :: UserType.

There is also QVariant :: typeName () , which returns the type name as a string.

EDIT:

This probably depends on how you install QVariant. Directly using QVariant :: QVariant (int type, const void * copy) is not recommended.

Let's say I have three types:

 class MyFirstType { public: MyFirstType(); MyFirstType(const MyFirstType &other); ~MyFirstType(); MyFirstType(const QString &content); QString content() const; private: QString m_content; }; Q_DECLARE_METATYPE(MyFirstType); 

Third without Q_DECLARE_METATYPE

I store them in QVariant:

  QString content = "Test"; MyFirstType first(content); MySecondType second(content); MyThirdType third(content); QVariant firstVariant; firstVariant.setValue(first); QVariant secondVariant = QVariant::fromValue(second); int myType = qRegisterMetaType<MyThirdType>("MyThirdType"); QVariant thirdVariant(myType, &third); // Here the type isn't checked against the data passed qDebug() << "typeName for first :" << firstVariant.typeName(); qDebug() << "UserType :" << firstVariant.userType(); qDebug() << "Type : " << firstVariant.type(); [...] 

I get:

 typeName for first : MyFirstType UserType : 256 Type : QVariant::UserType typeName for second : MySecondType UserType : 257 Type : QVariant::UserType typeName for third : MyThirdType UserType : 258 Type : QVariant::UserType 
+11
source share

All Articles