首页 > 解决方案 > 如何为 Qt Quick Designer 模拟 C++ 枚举?

问题描述

我有一个这样定义的 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 中的“设计”选项卡)中打开该 QML 文件时,它拒绝加载文件并显示QML module not found (SectionIdImportName),因为 Designer 不运行任何 C++ 代码。

如何让 Designer 使用使用 C++ 枚举的 QML 文件?

我知道QML_DESIGNER_IMPORT_PATHQML枚举属性。我试图通过这样一个 QML 枚举来“模拟” C++ 枚举,只是为了设计器,但是,这些枚举的值是这样使用的QMLType.EnumType.EnumValue,而 C++ 枚举值必须用EnumType.EnumValue. 看起来代码可以兼容 C++ 枚举或 QML 枚举,但不能同时兼容。

我正在使用 Qt 5.11,很快就会升级到 5.12。

标签: c++qtqmlqt-creatorqt-designer

解决方案


我让它在运行时和设计器上都工作,枚举封装在一个类中:

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 中像预期的那样使用:

import your.namespace 1.0

Item {
    property int test: SectionId.SomeValue
}

请注意,未使用枚举的名称。

您可以在同一个类中添加更多枚举,但名称可能会发生冲突(域方面或文本方面)


推荐阅读