构建 QML 应用程序

构建 C++ 控制台应用程序中,我们展示了一个简单控制台应用程序的 CMakeLists.txt 文件。现在我们将创建一个 QML 应用程序,使用 Qt Quick模块的 QML 应用程序。

这是完整的项目文件:

cmake_minimum_required(VERSION 3.16)

project(hello VERSION 1.0 LANGUAGES CXX)

find_package(Qt6 6.2 COMPONENTS Quick Gui REQUIRED)

qt_standard_project_setup(REQUIRES 6.5)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

qt_add_executable(myapp
    main.cpp
)

qt_add_qml_module(myapp
    URI hello
    QML_FILES
        main.qml
        FramedImage.qml
    RESOURCES
        img/world.png
)

target_link_libraries(myapp PRIVATE Qt6::Gui Qt6::Quick)

让我们来看看我们所做的改动。在find_package 调用中,我们将Core 替换为Quick 。这将定位Qt6Quick 模块,并提供我们稍后链接的Qt6::Quick 目标。

find_package(Qt6 6.2 COMPONENTS Quick Gui REQUIRED)

我们调用qt_standard_project_setup,并指定CMAKE_CXX_STANDARDCMAKE_CXX_STANDARD_REQUIRED 。通过传递REQUIRES 6.5qt_standard_project_setup ,我们选择了qt_add_qml_module 的有用默认值。它启用了版本 6.5 以下的所有Qt CMake 策略。尤其是QTP0001,它定义了 QML 模块的默认资源前缀,确保模块最终会被导入到 QML 引擎的默认导入路径中。

qt_standard_project_setup(REQUIRES 6.5)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

请注意,应用程序仍将链接Qt6::Core ,因为Qt6::Quick 依赖于它。

qt_add_executable创建并最终确定应用程序目标:

qt_add_executable(myapp
    main.cpp
)

qt_add_qml_module传递可执行文件的目标、URI、模块版本和 QML 文件列表,以确保 myapp 成为 QML 模块。这将 QML 文件放入资源文件系统中的qrc:/qt/qml/${URI} 。此外,qt_add_qml_module 还可确保qmlcachegen 运行。此外,它还创建了myapp_qmllint 目标,在 QML_FILES 中的文件上运行qmllint

qt_add_qml_module(myapp
    URI hello
    QML_FILES
        main.qml
        FramedImage.qml
    RESOURCES
        img/world.png
)

通过添加引用资源,它们会自动添加到应用程序中,与 QML 文件的根路径相同,也在资源文件系统中。通过保持资源系统中的路径与源代码和编译目录中的路径一致,我们能确保始终找到图像,因为它是相对于 FramedImage.qml 解析的。如果我们从资源文件系统加载 main.qml,它指的是资源文件系统中的图像;如果我们使用qml 工具查看,它指的是实际文件系统中的图像。

target_link_libraries 命令中,我们链接的是Qt6::Quick 而不是Qt6::Core

target_link_libraries(myapp PRIVATE Qt6::Gui Qt6::Quick)

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