c++ - 如何为 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_PATH
QML枚举属性。我试图通过这样一个 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 中像预期的那样使用:
import your.namespace 1.0
Item {
property int test: SectionId.SomeValue
}
请注意,未使用枚举的名称。
您可以在同一个类中添加更多枚举,但名称可能会发生冲突(域方面或文本方面)
推荐阅读
- python - 使用 input() 接收整数和字符串并检查条件
- powershell - 如何通过同一文件夹中的 .vbs 文件运行 .ps1 文件?
- c# - 如何使用 get set 方法将数据从类传递到表单?
- python-3.x - 如何解决 vs code stdio 上与 pylint installltion 相关的错误
- java - Flutter 错误:无法下载 bundletool.jar (com.android.tools.build:bundletool:0.9.0)
- angular - 打开 sans font css Node Module 后 Angular Project 托管不起作用
- kubernetes - 使用 NodePort 类型服务公开私有 kubernetes 集群
- javascript - 解析错误:无效或意外的令牌
- mysql - 无法在 case when 语句中放置子查询条件
- laravel - Laravel 通过模型存储数据