如何在其他 cpp 文件中使用嵌套Q_ENUM,而不是在 qml 中?
How to use nested Q_ENUM in other cpp file, not in qml?
我想从其他类访问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
相关文章:
- 从C++实例化QML
- enum是C++中的宏变量还是整数变量
- 使用CMake创建QML插件
- 是否可以从int转换为enum类类型
- QT通过C++添加映射QML项目
- 如何在没有信号的情况下从C++执行QML插槽
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type
- QML按钮点击功能执行顺序
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 建议在运行时将带有类实例的列表从c++导入qml
- Qt Quick-如何仅从c++代码与qml属性交互
- 在C++中,将int值赋给enum,反之亦然
- 如何将带有自定义对象的容器从C++传递到QML
- 两个 COM 组件中 ENUM 的重复条目
- QML 使用带有参数C++函数
- 最佳做法是从另一个线程访问 qml 中的Q_PROPERTY
- 如何从C++端挂接到 QML 项的 onClick 事件
- 在 qml 中使用 Q_ENUM 和 Q_PROPERTY 作为枚举类
- 从C++更改 QML 图像源
- 使用 enum 参数将 C++ 对象信号连接到 QML 信号处理程序