将 Qt::[Enum/Flag] 注册为 QtMetaType
Registering Qt::[Enum/Flag] as QtMetaType
我想创建一个对象来访问 QMouseEvent
的值。
这个事件有例如
Qt::MouseButton QMouseEvent::button() const
所以我添加到我的 class MyQMLMouseEvent
Q_PROPERTY(Qt::MouseButton button READ button)
和必要的getter.
我预计,在 QML 方面,我可以这样使用它:
myQmlMouseEvent.button === Qt.ButtonLeft
因为 Qt.ButtonLeft
可用,例如使用 MouseArea
的 clicked
信号。
现在进行测试,我处理在 QML 中传递此 MyQMLMouseEvent
实例的信号,如下所示:
onMyQMLMousEvent: console.log(JSON.stringify(myMouseEvent))
打印大多数属性,但在 Qt::MouseButton
类型上失败。为此,它给了我错误:
QMetaProperty::read: Unable to handle unregistered datatype 'Qt::MouseButton'
for property 'MyQMLMouseEvent::button'
Here 他们说我可以通过调用 qRegisterMetaType
来注册这些类型来解决这个问题。
我不确定在这种情况下这是否正确或者是否适用于
Qt
在 QML 中已经可用 - 所以再次注册它的一部分对我来说似乎是错误的?
- 我可以
qRegisterMetaType
枚举和标记一些 class 我几乎无法控制的东西吗?
有趣的是:失败的是 Qt::MouseButton
和 Qt::MouseEventFlags
而不是 Qt:MouseButtons
(这只是 Qt::MouseButton
的别名)。
这意味着我可以通过将类型更改为复数来绕过 Qt::MouseButton
的问题,并且 Qt::MouseEventFlags
可以作为 int
传递,因为它在 QML 中确实不可用(应该是 Qt.MouseEventCreatedDoubleClick
)
仍然,出于好奇,如果将来可能需要: 从 Qt
命名空间,如果他们还没有注册?
每当我使用一些完全不同的 class.
时,我真的不想每次都在我的 main.cpp
中注册它们
将 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")
}
我想创建一个对象来访问 QMouseEvent
的值。
这个事件有例如
Qt::MouseButton QMouseEvent::button() const
所以我添加到我的 class MyQMLMouseEvent
Q_PROPERTY(Qt::MouseButton button READ button)
和必要的getter.
我预计,在 QML 方面,我可以这样使用它:
myQmlMouseEvent.button === Qt.ButtonLeft
因为 Qt.ButtonLeft
可用,例如使用 MouseArea
的 clicked
信号。
现在进行测试,我处理在 QML 中传递此 MyQMLMouseEvent
实例的信号,如下所示:
onMyQMLMousEvent: console.log(JSON.stringify(myMouseEvent))
打印大多数属性,但在 Qt::MouseButton
类型上失败。为此,它给了我错误:
QMetaProperty::read: Unable to handle unregistered datatype
'Qt::MouseButton'
for property'MyQMLMouseEvent::button'
Here 他们说我可以通过调用 qRegisterMetaType
来注册这些类型来解决这个问题。
我不确定在这种情况下这是否正确或者是否适用于
Qt
在 QML 中已经可用 - 所以再次注册它的一部分对我来说似乎是错误的?- 我可以
qRegisterMetaType
枚举和标记一些 class 我几乎无法控制的东西吗?
有趣的是:失败的是 Qt::MouseButton
和 Qt::MouseEventFlags
而不是 Qt:MouseButtons
(这只是 Qt::MouseButton
的别名)。
这意味着我可以通过将类型更改为复数来绕过 Qt::MouseButton
的问题,并且 Qt::MouseEventFlags
可以作为 int
传递,因为它在 QML 中确实不可用(应该是 Qt.MouseEventCreatedDoubleClick
)
仍然,出于好奇,如果将来可能需要: 从 Qt
命名空间,如果他们还没有注册?
每当我使用一些完全不同的 class.
main.cpp
中注册它们
将 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")
}