如何在其他 cpp 文件中使用嵌套Q_ENUM,而不是在 qml 中?

How to use nested Q_ENUM in other cpp file, not in qml?

本文关键字:ENUM qml 嵌套 cpp 其他 文件      更新时间:2023-10-16

我想从其他类访问Q_ENUM类内枚举。我是否使用 cpp 枚举语义(如 className::enumName(来访问它?

我是否必须在"B.cpp"中包含"A.h"才能访问 A 的枚举?

还有其他方法可以使用Q_ENUM或QT库访问A的枚举吗?

// A.h
class A 
{
enum enum_A
{
E_OP_0 = 0,
...
};
Q_ENUM(enum_A)
};
// B.cpp
void B::changeOption()
{
// problem: B.cpp cannot identify enum_A
qml->setProperty("property", QVariant{enum_A::E_OP_0});
}

谢谢

我是否必须在"B.cpp"中包含"A.h"才能访问A的枚举?

那肯定是最容易的!

还有其他方法可以使用Q_ENUM或QT库访问A的枚举吗?

首先,要在Qt Meta系统中注册enum_A(以及Q_ENUM((才能工作(,A类需要从QObject继承(并具有Q_OBJECT宏(或具有Q_GADGET宏。或者A可以是一个namespace,可以使用Q_ENUM_NS()来注册枚举。

通常不需要在枚举上使用qRegisterMetaType<>(),但是这样做了,那么这个"愚蠢的技巧"就会起作用(我不知道为什么有人会去找麻烦,但无论如何(:

#include <QObject>
#include <QDebug>
class A
{
Q_GADGET
public:
enum enum_A {
E_OP_0 = 0
};
Q_ENUM(enum_A)
};
int main(int argc, char *argv[])
{
// Register the enum type. Here we have to have/know class A declaration.
qRegisterMetaType<A::enum_A>();  
// The code below could be elsewhere and not include "class A" header/declaration. 
// We only need to know the full name of the enum at this point.
const int enumType = QMetaType::type("A::enum_A");  // The registered type ID.
// Get meta object of the class/namespace which owns the enum
const QMetaObject *metaObj = QMetaType::metaObjectForType(enumType);
if (!metaObj) {
qWarning() << "Could not get the meta object for enum type.";
return 1;
}
// Index of enum within the meta object data
const int enumIdx = metaObj->indexOfEnumerator("enum_A");
// And finally meta data about the enum itself
const QMetaEnum metaEnum = metaObj->enumerator(enumIdx);
qDebug() << "Enum name:" << metaEnum.name() << "n" <<
"Key count:" << metaEnum.keyCount() << "n" <<
"Name of first key:" << metaEnum.key(0) << "n" <<
"Value of E_OP_0:" << metaEnum.keyToValue("E_OP_0");
return 0;
}

输出:

枚举名称:enum_A
密钥计数:1
第一个密钥的名称:E_OP_0
E_OP_0的值:0