View Full Version : Exposing a Q_ENUM to QML

16th December 2010, 16:20
I have an QObject derived class, which I want to use in QML. It has no UI component, just some properties, one of which is of type 'MyEnum'. MyEnum is declared with the Q_ENUMS() macro..

class MyClass : public QObject {

MyClass() : t(FirstValue) { }
enum myEnum { InvalidValue, FirstValue, SecondValue } ;

testType testVal() const { return t; }
Q_PROPERTY(myEnum testVal READ testVal NOTIFY testValChanged)
testType t;

void testValChanged();

Now I inject this QObject into my main.qml using setContextProperty(). All the regular properties work fine, and when ask for the property of type 'MyEnum'.. I get the integer value, which ok, not so bad.. but there's no way to get the Key names. Trying to access 'MyObject.InvalidValue , MyObject.FirstValue etc return undefined.

It differs from doc.qt.nokia.com/4.7-snapshot/qtbinding.html#using-enumerations-of-a-custom-type (http://doc.qt.nokia.com/4.7-snapshot/qtbinding.html#using-enumerations-of-a-custom-type)
In the example, the object is created from QML rather than C++, and the enumeration (defined in C++) is used freely..

Is this expected behavior? A work-around would be an extra property returning the string name. Any other ways?

17th December 2010, 13:18
Ah, missed something obvious, you need to access the Enum with through the class name, rather than the object name:

MyClass.FirstValue returns '1'

MyObject.FirstValue returns 'undefined'