构建 QML 应用程序

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

以下是完整的项目文件:

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 目标——您可以运行该目标,以便从qmllint 获取有关.qml 文件的额外建议。

target_link_libraries(helloworld PRIVATE Qt6::Quick)

在target_link_libraries() 命令中,我们将可执行文件与Qt6::Quick 关联。这也会自动将可执行文件与Qt6::Quick 所依赖的目标进行关联,包括Qt6::Qml 和Qt6::Core 。

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