QT6 源(39):宏 Q_ENUM(...)用于往元对象系统里注册自己定义的枚举类

(1)
This macro registers an enum type with the meta-object system. It must be placed after the enum declaration in a class that has the Q_OBJECT or the Q_GADGET macro. For namespaces use Q_ENUM_NS() instead.
这个宏在元对象系统中注册了一个枚举类型。它必须在具有Q OBJECT或QGADGET宏的类中的枚举声明之后放置。对于命名空间,请使用QENUM NS()代替。

++举例:

 class MyClass : public QObject
 {
     Q_OBJECT

 public:
     MyClass(QObject *parent = nullptr);
     ~MyClass();

     enum Priority { High, Low, VeryHigh, VeryLow };
     Q_ENUM(Priority)
     
     Priority  priority() const;
     void   setPriority(Priority priority);
     
 };

使用 Q_ENUM 声明的枚举类型,它们的 QMetaEnum 会在包含的 QMetaObject 中注册。您还可以使用 QMetaEnum::fromType()来获取 QMetaEnum。
注册的枚举类型也会自动注册到Qt元类型系统中,使它们被QMetaType所知晓,而无需使用)DECLARE METATYPE)。这将启用有用的功能;例如,如果用于0Variant,则可以将它们转换为字符串。同样,将它们传递给QDebug将打印出它们的名称。
请注意,枚举值在元对象系统中存储为带符号的整数。将具有超出整数有效范围的值的枚举注册将导致溢出,并且当通过元对象系统访问它们时可能会导致未定义的行为。例如,QML确实通过元对象系统访问已注册的枚举。

Enumerations that are declared with Q_ENUM have their QMetaEnum registered in the enclosing QMetaObject. You can also use QMetaEnum::fromType() to get the QMetaEnum.

Registered enumerations are automatically registered also to the Qt meta type system, making them known to QMetaType without the need to use Q_DECLARE_METATYPE(). This will enable useful features; for example, if used in a QVariant, you can convert them to strings. Likewise, passing them to QDebug will print out their names.

Mind that the enum values are stored as signed int in the meta object system. Registering enumerations with values outside the range of values valid for int will lead to overflows and potentially undefined behavior when accessing them through the meta object system. QML, for example, does access registered enumerations through the meta object system.

(2)看看源码:

// The following macros can be defined by tools that understand Qt
// to have the information from the macro.
#ifndef QT_ANNOTATE_CLASS
# define QT_ANNOTATE_CLASS(type, ...)
#endif

#define Q_ENUMS(x) QT_ANNOTATE_CLASS(qt_enums, x) //这里解释了宏 Q_ENUMS(x) 的意思

#define Q_ENUM_IMPL(ENUM) \ //看起来此宏展开后会为新定义的 ENUM 枚举类定义两个全局函数
    friend constexpr const QMetaObject * qt_getEnumMetaObject(ENUM) noexcept \
    { return &staticMetaObject; } \
    \
    friend constexpr const     char    * qt_getEnumName(ENUM) noexcept \
    { return #ENUM; }
    
#define Q_ENUM(x) Q_ENUMS(x) Q_ENUM_IMPL(x) //本宏被展开为两个宏

(3)

谢谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值