我有一个像这样定义的C ++枚举:
namespace SectionIdNamespace
{
Q_NAMESPACE
enum SectionId {
SomeValue
};
Q_ENUM_NS(SectionId)
};
我注册枚举如下:
qmlRegisterUncreatableMetaObject(
SectionIdNamespace::staticMetaObject,
"SectionIdImportName",
1, 0,
"SectionId",
"Error: only enums"
);
并在QML中使用它:
import SectionIdImportName 1.0
....
SectionId.SomeValue
在Qt Quick Designer(Qt Creator中的“Design”选项卡)中打开该QML文件时,它拒绝加载该文件并说QML module not found (SectionIdImportName)
,因为Designer不运行任何C ++代码。
如何让Designer使用那个使用C ++枚举的QML文件?
我知道QML_DESIGNER_IMPORT_PATH
和QML enumeration attributes。我试图通过这样的QML枚举“模拟”C ++枚举,但是,这些枚举的值像QMLType.EnumType.EnumValue
一样使用,而C ++枚举值必须仅使用EnumType.EnumValue
。看起来代码可以与C ++枚举或QML枚举兼容,但不能同时兼容。
我正在使用Qt 5.11,很快升级到5.12。
我在运行时和设计器上都使用了封装在类中的枚举:
class SectionIdWrapper : public QObject
{
Q_OBJECT
public:
enum class SectionIdEnum {
SomeValue
};
Q_ENUM(SectionIdEnum);
};
并注册如下:
qmlRegisterUncreatableType<SectionIdWrapper>("your.namespace", 1, 0, "SectionId", "Error: only enum");
像Qml一样在Qml中使用:
import your.namespace 1.0
Item {
property int test: SectionId.SomeValue
}
请注意,不使用枚举的名称。
您可以在同一个类中添加更多枚举,但随后名称可能会发生冲突(无论是域还是文本)