将Qt :: [Enum / Flag]注册为QtMetaType

时间:2017-09-12 09:10:08

标签: c++ qt qml qt5 qtquick2

我想创建一个对象来访问QMouseEvent的值。

此事件有例如

Qt::MouseButton QMouseEvent::button() const

所以我添加到我的班级MyQMLMouseEvent

Q_PROPERTY(Qt::MouseButton button READ button)

和必要的吸气剂。

我预计,在QML方面,我可以这样使用它:

myQmlMouseEvent.button === Qt.ButtonLeft

Qt.ButtonLeft可用,例如使用使用MouseArea' clicked信号。

现在进行测试,我处理的信号是我在QML中传递这个MyQMLMouseEvent - 实例,如下所示:

onMyQMLMousEvent: console.log(JSON.stringify(myMouseEvent))

打印大多数属性,但在Qt::MouseButton类型上失败。为此,它给了我错误:

  

QMetaProperty :: read:无法处理属性'Qt::MouseButton'的未注册数据类型'MyQMLMouseEvent::button'

Here他们说我可以通过致电qRegisterMetaType来注册这些类型来解决这个问题 我不确定在这种情况下这是正确的还是可以用于

  • Qt已经在QML中提供了 - 所以再次注册部分内容似乎对我不对了?
  • 我可以qRegisterMetaType枚举一些我无法控制的课程中的标志吗?

有趣的是:失败的是Qt::MouseButtonQt::MouseEventFlags,但不是Qt:MouseButtons(这只是Qt::MouseButton的别名)。
这意味着我可以通过将类型更改为复数来绕过Qt::MouseButton的问题,Qt::MouseEventFlags可以作为int传递,因为它确实在QML中不可用(应该是{ {1}})

仍然只是出于好奇,以及将来是否有必要: Qt.MouseEventCreatedDoubleClick命名空间注册枚举和标志的正确方法是什么还没注册? 每当我使用一些完全不同的课时,我都不想每次都在Qt注册它们。

1 个答案:

答案 0 :(得分:3)

Q_PROPERTY类型设置为int

没有必要声明或注册任何额外的元类型只是为了使用枚举。

C ++

class MouseButtonObject : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int button READ button)

public:
    explicit MouseButtonObject(QObject *parent = nullptr);

    Qt::MouseButton button() { return Qt::LeftButton; }
};

QML

if (mouseButtonObject.button === Qt.LeftButton) {
    console.log("button is Left Button")
}