将 Qt::[枚举/标志] 注册为 QtMetaType

Registering Qt::[Enum/Flag] as QtMetaType

本文关键字:注册 标志 QtMetaType Qt 枚举      更新时间:2023-10-16

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

此事件具有例如

Qt::MouseButton QMouseEvent::button() const

所以我在我的班级里增加了MyQMLMouseEvent

Q_PROPERTY(Qt::MouseButton button READ button)

和必要的吸气剂。

我期望,在QML方面,我可以这样使用它:

myQmlMouseEvent.button === Qt.ButtonLeft

因为Qt.ButtonLeft可用,例如与MouseAreaclicked信号一起使用。

现在为了进行测试,我在 QML 中处理我传递此MyQMLMouseEvent实例的信号,如下所示:

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

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

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

在这里,他们说我可以通过调用qRegisterMetaType来注册这些类型来解决此问题。
我不确定在这种情况下这是否正确,甚至适用于

  • Qt已经在 QML 中可用 - 所以再次注册其中的一部分对我来说似乎是错误的?
  • 我可以从我几乎无法控制的某个类中qRegisterMetaType枚举和标志吗?

令人不安的是:失败的是Qt::MouseButtonQt::MouseEventFlags,但不是那么Qt:MouseButtons(这只是Qt::MouseButton的别名)。
这意味着我可以通过将类型更改为复数来规避Qt::MouseButton的问题,并且Qt::MouseEventFlags可以int传递,因为它确实在 QML 中不可用(应该Qt.MouseEventCreatedDoubleClick)

不过,只是出于好奇,如果将来有必要:如果尚未注册枚举和标志,Qt命名空间注册枚举和标志的正确方法是什么? 每当我使用一些完全不同的类时,我真的不想每次在我的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")
}