Qt property system: access enumerations as string

  • Hi fellows!

    I have probably a novice question in here. I'm using the property system to share settings between different class.

    I need an enumeration and basically followed the documentation example:
    @class MyClass : public QObject
    Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)

    MyClass(QObject *parent = 0);

     enum Priority { High, Low, VeryHigh, VeryLow };
     void setPriority(Priority priority)
         m_priority = priority;
         emit priorityChanged(priority);
     Priority priority() const
     { return m_priority; }

    void priorityChanged(Priority);

    Priority m_priority;

    @MyClass *myinstance = new MyClass;
    QObject *object = myinstance;

    object->setProperty("priority", "VeryHigh");@

    Where I don't find information is how to get in this case "priority" returning for example "VeryHigh" this QVariant instead of 2
    @object->property("priority").toString() == "VeryHight";@

    Or did I get it wrong?

    Thanks for any help,

  • One thing I found (of course from web) is

    #include <QMetaObject>
    #include <QMetaEnum>

    QMetaObject metaObject = MyClass::staticMetaObject;
    QMetaEnum metaEnum = metaObject.enumerator( metaObject.indexOfEnumerator( "Priority" ) );
    MyClass* myinstance = new MyClass( 0 );
    myinstance->setPriority( MyClass::VeryHigh );
    QString enumVal = QString( metaEnum.valueToKey( myinstance->property( "priority" ).toInt() ) );


    The other way would be constructing a method to convert enum to QString kind of mapping method to map enum value to respective QString.

  • Thanks!

    I'll give it a go.

Log in to reply