构建 QML 应用程序

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

下面是完整的项目文件:

cmake_minimum_required(VERSION 3.16)

project(helloworld VERSION 1.0.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt6 6.5 COMPONENTS Quick REQUIRED)

qt_standard_project_setup(REQUIRES 6.5)

qt_add_executable(helloworld
    main.cpp
)

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

target_link_libraries(helloworld PRIVATE Qt6::Quick)

与控制台应用程序CMakeLists.txt 相比,我们做了哪些改动?

    ...
find_package(Qt6 6.5 COMPONENTS Quick REQUIRED)

find_package() 调用中,我们将Core 替换为Quick 。因此,CMake 将加载Qt6Quick 模块,并提供我们稍后链接的Qt6::Quick 目标。CMake 还会自动加载 Quick 依赖的软件包,比如Qt6Qml ,它定义了我们下面使用的qt_add_qml_module()命令。

我们还需要 Qt 6.5 或更新版本。

qt_standard_project_setup(REQUIRES 6.5)

qt_standard_project_setup()命令为典型的 Qt 应用程序设置整个项目的默认值。通过添加REQUIRES 6.5 ,我们启用了QTP0001 策略,它为qt_add_qml_module() 创建的 QML 模块定义了默认资源前缀。

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

qt_add_qml_module()为可执行文件添加了一个名为hello 的 QML 模块,该模块由两个 QML 文件和一个图像组成。由于使用了QTP0001,该模块在资源文件系统的qrc:/qt/qml/hello 中可用,而qrc:/qt/qml/ 是 QML 引擎的默认导入路径之一。

qt_add_qml_module()还会执行一些优化步骤,如运行QML 脚本编译器,以及定义一个helloworld_qmllint target,运行该目标可从qmllint 获得有关.qml 文件的其他建议。

target_link_libraries(helloworld PRIVATE Qt6::Quick)

target_link_libraries() 命令中,我们将可执行文件与Qt6::Quick 进行链接。这也会自动链接Qt6::Quick 依赖的目标,包括Qt6::QmlQt6::Core

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