构建可重用的 QML 模块
下面的例子演示了如何创建一个库,把 C++ 暴露给 QML。示例的目录结构如下:
├── CMakeLists.txt └── example └── mylib ├── CMakeLists.txt ├── mytype.cpp ├── mytype.h
顶级CMakeLists.txt
文件使用qt_standard_project_setup 进行一些基本设置,然后使用add_subdirectory
包括 mylib 中的文件:
cmake_minimum_required(VERSION 3.16) project(qmlmodule VERSION 1.0.0 LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) find_package(Qt6 REQUIRED COMPONENTS Qml) qt_standard_project_setup(REQUIRES 6.5) add_subdirectory(example/mylib)
子目录的结构与 QML 模块的 URI 相对应,只是用斜线代替了点。这与引擎在导入路径中搜索模块时使用的逻辑相同。遵循这种子目录结构有助于工具的开发。
mytype.h
该子目录中的"...... "声明了一个类,并使用声明式注册宏将其暴露给引擎。
在子目录CMakeLists.txt
中,我们调用qt_add_qml_module。与构建 QML 应用程序相比,调用方式略有不同:
qt_add_qml_module(mylib URI example.mylib VERSION 1.0 SOURCES mytype.h mytype.cpp QML_FILES MyQmlType.qml )
mylib
的目标尚未创建。当传递给qt6_add_qml_module
的目标不存在时,它会自动创建一个库目标。这避免了单独调用qt_add_library。要注册用 C++ 定义的 QML 类型,请将它们的头文件和源文件作为参数添加到 SOURCES 参数。
构建项目时,除库外,还会构建 QML 插件。插件的自动生成类从QQmlEngineExtensionPlugin 扩展而来。mylib 库本身已经包含了向引擎注册类型的代码。不过,这只在我们可以链接到该库的情况下有用。要使模块在qml
、QML Runtime 工具加载的 QML 文件中可用,需要一个可加载的插件。插件负责与库进行实际链接,并确保类型得到注册。
请注意,只有当模块除了注册类型之外不做任何事情时,才有可能自动生成插件。initializeEngine
qt6_add_qml_module支持NO_GENERATE_PLUGIN_SOURCE
。
此外,遵循目录布局约定有助于工具的开发。该布局会在构建目录中得到反映。这意味着您可以将构建目录的路径传递给 QML 工具(通过-I
标志),它就能找到插件。
© 2025 The Qt Company Ltd. 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.