[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:
@
QVariant variant = enumValue; // EnumType enumValue
// ...
EnumType anotherValue = static_cast<EnumType>(variant.toInt());
@
Is there a cute way to obtain enum value from QVariant using QVariant::value()? -
Did you declare the enum with "Q_DECLARE_METATYPE()":http://doc.qt.nokia.com/4.7/qmetatype.html#Q_DECLARE_METATYPE ? 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[])
{
QVariant v1 = Test2::V1;
qDebug() << v1.toInt(0) << v1.valueTest2::Test();QVariant v2 = qVariantFromValue(Test2::V1); qDebug() << v2.toInt(0) << v2.value<Test2::Test>(); return 0;
}
@The output is:
@100 0
0 100 @
Does that help? -
Hi,
one side note: when using Q_DECLARE_METATYPE() on an enum you define it as user type in the Qt meta system. The drawback is that e.g. QMetaProperty::isEnumType() won't work anymore because its now a user defined type. Qt designer won't accept it either.
-
Please elaborate.
@
class Test : public QObject
{
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
@ -
@Lukas: What do you mean by "Please elaborate"?
-
[quote author="loladiro" date="1307893708"]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[])
{
QVariant v1 = Test2::V1;
qDebug() << v1.toInt(0) << v1.valueTest2::Test();QVariant v2 = qVariantFromValue(Test2::V1); qDebug() << v2.toInt(0) << v2.value<Test2::Test>(); return 0;
}
@
[/quote]Thank you. The enum doesn't need to be wrapped in a class.
Following works:
@#include <QtDebug>
enum Test { V1=100, V2, V3 };
Q_DECLARE_METATYPE(Test)
int main(int argc, char *argv[])
{
QVariant v1 = V1;
qDebug() << v1.toInt(0) << v1.value<Test>();QVariant v2 = QVariant::fromValue(V1); qDebug() << v2.toInt(0) << v2.value<Test>();
}
@