在 QML 中使用枚举分配或更改 int 属性

Assigning or changing int property using enum inside QML

考虑这个简单的枚举 class:

#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

取自 docs:

Note: The names of enum values must begin with a capital letter in order to be accessible from QML.

这回避了问题:为什么它在 属性 绑定中起作用?我不知道,可能是 Qt 错误。