Using c++ enum in QML as string

不问归期 提交于 2019-12-21 04:57:19

问题


What I would like to do is use the below enum in c++:

class MyClass : public QQuickItem {
    Q_OBJECT
    Q_PROPERTY(MyEnum enumValue READ getEnumValue)

public:
    enum MyEnum{
        MyEnumElement = 0
    };
    Q_ENUM(MyEnum)

slots:
    MyEnum getEnumValue(){
        return enumValue;
    }

private: 
    MyEnum enumValue = MyEnumElement;
};

In such a way in QML:

MyClass {
    id: myClass
}

Text {
    text: "enumValue is: " + myClass.enumValue
}

That would result in enumValue is MyEnumElement instead of enumValue is 0 which is the case now. The solution I have now is the following, however inelegant:

class MyClass : public QQuickItem {
    Q_OBJECT
    Q_PROPERTY(MyEnum enumValue READ getEnumValue)

public:
    enum MyEnum{
        MyEnumElement = 0
    };
    Q_ENUM(MyEnum)
    QMetaEnum MyEnum_MetaEnum = QMetaEnum::fromType<MyEnum>();
    Q_INVOKABLE QString getEnumString(MyEnum enumVal){
        return MyEnum_MetaEnum.valueToKey(enumVal);
    }

slots:
    MyEnum getEnumValue(){
        return enumValue;
    }

private: 
    MyEnum enumValue = MyEnumElement;
};

And:

MyClass {
    id: myClass
}

Text {
    text: "enumValue is: " + myClass.getEnumString(myClass.enumValue)
}

Is there a better way to do this?


回答1:


I found the following to work:

class MyClass : public QQuickItem {
    Q_OBJECT
    Q_PROPERTY(QVariant enumValue READ getEnumValue)

public:
    enum MyEnum{
        MyEnumElement = 0
    };
    Q_ENUM(MyEnum)

slots:
    QVariant getEnumValue(){
        return QVariant::fromValue(enumValue);
    }

private: 
    MyEnum enumValue = MyEnumElement;
};

QML side:

MyClass {
    id: myClass
}

Text {
    text: "enumValue is: " + myClass.enumValue.toString()
}

Using without .toString() still causes the QVariant to be cast to an int. I'm still open to more elegant solutions.

Edit:

As expected, this breaks switch and === on the QML/Javascript side. switch(enumValue.valueOf()) and == must be used when comparing to enum ints exported by Q_ENUM(), such as MyClass.MyEnumElement:

switch(myClass.enumValue.valueOf()){
    case MyClass.MyEnumElement:
        ...
        break;
}

and

if(myClass.enumValue == MyClass.MyEnumElement)
    ...


来源:https://stackoverflow.com/questions/37663286/using-c-enum-in-qml-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!