Qt-Q_ENUM宏和QMetaEnum类

Q_ENUM是一个宏定义,它的作用是将一个枚举类型注册到元对象系统,从而能够通过QMetaEnum类获得一些关于enum类型的一些信息,例如获取enum类型的名称字符串,enum值和字符串互相转换,enum类型保存在QVariant中,enum值的个数,qDebug()打印enum值名称等等。

用法:在一个继承于QObject的子类中声明enum,然后在定义后面使用Q_ENUM宏注册enum类型。如下:

cpp 复制代码
class MyClass : public QObject
{
    Q_OBJECT

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

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

随后通过QMetaEnum获取enum类型的相关信息。

cpp 复制代码
QMetaEnum metaEnum = QMetaEnum::fromType<MyClass ::Priority >();
qDebug() << metaEnum.enumName();  // Priority
qDebug() << metaEnum.keyCount();  // 4
QString s = metaEnum.valueToKey(MyClass::Priority::Low;  // Low
int p = metaEnum.keyToValue(s);  // 1
MyClass::Priority e = (MyClass::Priority)p;
qDebug() << e; // 打印MyClass::Low而不是1
QVariant v = QVariant::fromValue(e);  // 保存在QVariant中

使用Q_ENUM声明的枚举类型已经在元对象系统中注册,不再需要使用Q_DELCARE_METATYPE。

相关推荐
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner4 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz9 天前
QML Hello World 入门示例
qt
xcyxiner12 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner13 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner13 天前
DicomViewer (添加模型类)3
qt
xcyxiner14 天前
DicomViewer (目录调整) 2
qt
xcyxiner14 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00616 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术16 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript