使用 QML 模块插件

QML 模块可使用C++ 插件,将 C++ 中定义的组件公开给Qt Quick 应用程序。

创建 QML 模块:

  1. 创建自定义组件,并将所有.qml 文件放到模块专用目录中。例如,imports\asset_imports
  2. 对于Qt Quick UI Prototype 项目(.qmlproject),在要使用模块的应用程序的 .qmlproject 文件中指定模块所在目录的路径,作为importPaths 变量的值。例如,importPaths: [ "imports", "asset_imports" ]
  3. 为模块创建qmldir 文件,并将其放在模块目录中。更多信息,请参阅模块定义 qmldir 文件
  4. 在模块目录下创建名为designer 的目录。
  5. 为模块创建.metainfo 文件,并将其放在designer 目录中。以 Qt XML 提供的 metainfo 文件(如qtquickcontrols2.metainfo )为例。
  6. 按照导入 QML 模块中的说明,将模块导入到项目中。

注意: 如果Qt Creator 找不到新的 QML 模块,请构建项目,然后转到Tools >QML/JS >Reset Code Model 重置代码模型。

使用 Qt 6.1 或更早版本进行开发

自 Qt 6.2 起,CMake 会自动生成qmltypesqmldir 文件。

生成类型描述文件

注册 QML 类型时,确保 QML 模块有plugins.qmltypes 文件。理想情况下,它应与qmldir 文件位于同一目录。qmltypes 文件描述了模块插件导出的组件,并在模块导入时由Qt Creator 加载。

更多信息,请参阅类型描述文件

自动转储插件

如果带有插件的模块缺少qmltypes 文件,Qt Creator 会尝试通过在后台运行qmldump 程序来自行生成临时文件。不过,这种自动转储是一种后备机制,有许多故障点,不能依赖它。

导入 QML 模块

默认情况下,Qt Creator 会在 Qt 的 QML 导入路径中查找 QML 模块。

如果您使用 qmake,而且您的应用程序添加了Qt Creator 应使用的其他导入路径,请在您应用程序的.pro 文件中使用QML_IMPORT_PATH 指定它们:QML_IMPORT_PATH += path/to/module

如果您使用 CMake,请在 CMakeLists.txt 文件中添加以下命令来设置 QML 导入路径:

set(QML_IMPORT_PATH ${CMAKE_SOURCE_DIR}/qml ${CMAKE_BINARY_DIR}/imports CACHE STRING "" FORCE)

导入路径会影响 CMake 项目构建的所有目标。

另请参阅 重置代码模型

Copyright © The Qt Company Ltd. and other contributors. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.