本页内容

用 CMake 将一切联系在一起

创建 QML 模块时,CMake 为正确注册 QML 类型、生成必要的元数据以及确保模块正确打包和部署提供了基础架构。本页概述了推荐的工作流程。

使用 qt_add_qml_module

qt_add_qml_module命令是创建 QML 模块的标准和推荐方式。它处理创建 QML 模块的所有复杂细节:

qt_add_qml_module(my_qml_module
    URI MyModule
    QML_FILES
        MyType.qml
        AnotherType.qml
    SOURCES
        mytype.cpp mytype.h
)

这条命令

  • 创建模块目标
  • 从 C++ 和 QML 文件注册 QML 类型
  • 生成 qmldir 文件
  • 处理类型注册
  • 设置正确的导入路径
  • 启用 QML 工具支持(qmllintqmlls 等)

进一步添加 QML 文件

对于在初始qt_add_qml_module 调用后添加的 QML 文件,请使用qt_target_qml_sources

qt_target_qml_sources(my_qml_module
    QML_FILES
        DynamicallyAddedType.qml
)

这可以根据平台、配置或其他因素来决定。

详细的 CMake 参考资料

有关所有 CMake 命令、属性、变量和策略的完整详情,请参阅CMake Integration for QML

另请参阅 QML 模块qt_add_qml_module

© 2026 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.