[Solved] QVariant and enums
It seems that QVariant::value() won’t work correctly with enums. It’s of course possible to use this, but it looks like hacking:
- // ...
- EnumType anotherValue = static_cast<EnumType>(variant.toInt());
Is there a cute way to obtain enum value from QVariant using QVariant::value()?
8 replies
Did you declare the enum with Q_DECLARE_METATYPE() [doc.qt.nokia.com] ? If that still doesn’t work you could wrap the enum in a struct (I know that works)
Consider the following example:
- class Test2
- {
- public:
- Test2() {}
- enum Test { V1=100, V2, V3 };
- };
- Q_DECLARE_METATYPE(Test2::Test)
- int main(int argc, char *argv[])
- {
- qDebug() << v1.toInt(0) << v1.value<Test2::Test>();
- qDebug() << v2.toInt(0) << v2.value<Test2::Test>();
- return 0;
- }
The output is:
- 100 0
- 0 100
Does that help?
Please elaborate.
- {
- Q_OBJECT
- Q_ENUMS(Value)
- Q_PROPERTY(Value value READ value WRITE setValue)
- public:
- enum Value { valueA, valueB, valueC };
- void setValue(Value value) { value_ = value; }
- Value value() const { return value_; }
- private:
- Value value_;
- };
- Q_DECLARE_METATYPE(Test::Value)
- qDebug() << Test().metaObject()->property(1).isEnumType(); // true
You must log in to post a reply. Not a member yet? Register here!



