在QML

时间:2015-07-29 07:18:18

标签: qt enums qml qtquick2

考虑这个简单的枚举类:

#include <QObject>
class BookTypes : public QObject
{
    Q_GADGET
    Q_ENUMS(AllBooksType)    

public:

    enum AllBooksType{
        eMagazine,
        eReference,
        eTextBook,
        eThesis
    };

signals:

public slots:

};

main()

中输入注册
qmlRegisterUncreatableType<BookTypes>("trial", 1, 0, "BookTypes", 
"Don't create qml instance for BookTypes");

这是样本QML:

Rectangle {
        id: rect
        x: 100; y: 100
        width: 100
        height: 70
        color: "PowderBlue"
        border.color: "RoyalBlue"
        border.width: 1
        radius: 3

        MouseArea{
            x: 0; y: 0
            height: parent.height
            width: parent.width
            property int bt: BookTypes.eTextBook //perfect. now bt is 2
            onClicked: {
                console.debug("old book type:- ")
                console.debug(bt) //prints 2
                console.debug("selected book type:- ")
                bt = BookTypes.eReference //gives error - why ?
                console.debug(BookTypes.eReference) //prints 'undefined'
                console.debug(bt)
            }
        }
    }

这意味着枚举已正确公开,因为它在

中成功初始化bt
property int bt: BookTypes.eTextBook

我不明白的是:当我尝试在处理程序中替换bt的值时,为什么它不可访问:

bt = BookTypes.eReference //gives error - why ?

如何将这样的enum作为Q_INVOKABLE方法的参数传递,例如:

console.debug(BookTypes.eReference) //prints 'undefined'
SomeObj.someCPPMethod(BookTypes.eReference) // sends 'undefined' and defaults to 0

1 个答案:

答案 0 :(得分:5)

取自docs

  

注意:枚举值的名称必须以大写字母开头才能从QML访问。

这提出了一个问题:为什么它在属性绑定中有效?我不知道,可能是Qt bug。