June 12, 2011

DSav DSav
Lab Rat
28 posts

[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:

  1.   QVariant variant = enumValue; // EnumType enumValue
  2.   // ...
  3.   EnumType anotherValue = static_cast<EnumType>(variant.toInt());

Is there a cute way to obtain enum value from QVariant using QVariant::value()?

8 replies

June 12, 2011

loladiro loladiro
Lab Rat
596 posts

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)

June 12, 2011

DSav DSav
Lab Rat
28 posts

Yes, I’ve definitely declared. Wrapping in a struct looks like a kind of hacking as well :)

June 12, 2011

loladiro loladiro
Lab Rat
596 posts

Consider the following example:

  1. class Test2
  2. {
  3. public:
  4.     Test2() {}
  5. enum Test { V1=100, V2, V3 };
  6. };
  7.  
  8. Q_DECLARE_METATYPE(Test2::Test)
  9.  
  10. int main(int argc, char *argv[])
  11. {
  12.     QVariant v1 = Test2::V1;
  13.     qDebug() << v1.toInt(0) << v1.value<Test2::Test>();
  14.  
  15.     QVariant v2 = qVariantFromValue(Test2::V1);
  16.     qDebug() << v2.toInt(0) << v2.value<Test2::Test>();
  17.     return 0;
  18. }

The output is:

  1. 100 0
  2. 0 100

Does that help?

June 12, 2011

DSav DSav
Lab Rat
28 posts

Yes, that is helpful, thanks.

July 12, 2012

ViRuSTriNiTy ViRuSTriNiTy
Lab Rat
7 posts

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.

July 12, 2012

Lukas Geyer Lukas Geyer
Dinosaur Breeder
2074 posts

Please elaborate.

  1. class Test : public QObject
  2. {
  3.     Q_OBJECT
  4.     Q_ENUMS(Value)
  5.     Q_PROPERTY(Value value READ value WRITE setValue)
  6.  
  7. public:
  8.     enum Value { valueA, valueB, valueC };
  9.  
  10.     void setValue(Value value) { value_ = value; }
  11.     Value value() const { return value_; }
  12.  
  13. private:
  14.     Value value_;
  15. };
  16.  
  17. Q_DECLARE_METATYPE(Test::Value)
  18.  
  19. qDebug() << Test().metaObject()->property(1).isEnumType(); // true

September 6, 2012

ViRuSTriNiTy ViRuSTriNiTy
Lab Rat
7 posts

@Lukas: What do you mean by “Please elaborate”?

September 6, 2012

Andre Andre
Area 51 Engineer
6076 posts

It seems that Lukas is demonstrating with a small code snippet that the claim made by ViRuSTrNiTy is untrue.

 Signature 

Looking for Qt developers to join our team @ i-Optics: https://qt-project.org/forums/viewthread/25393/

 
  ‹‹ Question about QMessageBox obsolete members      How to set QIcon::fromTheme() to a label? ››

You must log in to post a reply. Not a member yet? Register here!