现代 QML 模块
Qt 6 中的 QML 模块变得更强大、更易用。下文将介绍如何对已使用qt_add_qml_module 的 QML 模块进行现代化。
另请参阅将 QML模块移植到 CMake,了解如何将 QML 模块移植到qt_add_qml_moduleCMake API。
使用 qt_standard_project_setup
qt_standard_project_setup设置现代 QML 模块所需的Qt CMake 策略等。要使 QML 模块现代化并遵循最佳实践,请在调用任何qt_add_qml_module之前,在项目的顶级CMakeLists.txt
文件中调用qt_standard_project_setup:
qt_standard_project_setup(REQUIRES 6.8)
使用新的标准资源路径前缀
随着QTP0001 的发布,QML 模块的标准资源路径从:/
移至:/qt/qml
。不要使用自定义资源前缀,也不要在引擎中扩展导入路径。删除所有qt_add_qml_module调用中的RESOURCE_PREFIX
参数,以及所有对QQmlEngine::addImportPath 或类似的调用。更改 C++ 和 QML 代码中的所有 qrc 路径,以使用新的资源路径前缀:
// C++ usages like: QUrl someUrl("qrc:/MyQmlModule/MyResource1.png"); // need to be changed to QUrl someUrl("qrc:/qt/qml/MyQmlModule/MyResource1.png"); // QML usages like: ":/MyQmlModule/MyResource1.png" // need to be changed to ":/qt/qml/MyQmlModule/MyResource1.png"
另请参阅 "使用 Qt Qml 资源系统"。
使用 loadFromModule 加载 QML 文件
使用默认导入路径,您可以使用loadFromModule
方法,例如QQmlApplicationEngine::loadFromModule,QQuickView::loadFromModule, 或QQmlComponent::loadFromModule 。
例如,使用loadFromModule
加载 QML 文件:
engine.load(QUrl(QStringLiteral("qrc:/MyQmlModule/Main.qml"))); // becomes engine.loadFromModule("MyQmlModule", "Main");
用 DEPENDENCIES TARGET 取代 OUTPUT_DIRECTORY 和 IMPORT_PATH
避免在qt_add_qml_module 中设置IMPORT_PATH
。相反,使用DEPENDENCIES TARGET
来声明对其他 QML 模块的依赖,这些模块在当前导入路径中找不到。
使用DEPENDENCIES TARGET
还可以省去QT_QML_OUTPUT_DIRECTORY
CMake 变量和qt_add_qml_module 的OUTPUT_DIRECTORY
参数,因此请删除它们的定义和用法。
例如
### in the CMakeLists.txt file defining the dependent QML module: # don't set QT_QML_OUTPUT_DIRECTORY and remove lines like these: set(QT_QML_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/qml) qt_add_qml_module(MyThirdPartyQmlLibraryDependency URI MyThirdPartyQmlLibraryDependency .... # custom output paths are obsolete due to DEPENDENCIES TARGET below, so remove: OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/qml } ### in the CMakeLists.txt file defining the QML module that uses the dependency: qt_add_qml_module(MyQmlLibrary URI MyQmlModule ... # replace import paths like these: IMPORT_PATH ${CMAKE_CURRENT_BINARY_DIR}/thirdparty/qml # with: DEPENDENCIES TARGET MyThirdPartyQmlLibraryDependency }
注意: 您可能需要在 CMakeLists.txt 中调用qt_add_qml_module之前调用add_subdirectory()
,以便DEPENDENCIES TARGET
找到目标。
有关如何声明模块依赖关系的更多信息,请参阅声明模块依赖关系。
另请参阅 Qt QML 的更改和将 QML 模块移植到 CMake。
© 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.