构建 QML 应用程序

构建 C++ 控制台应用程序 we showed the CMakeLists.txt file for a simple console application. We will now extend it to create a QML application that uses the Qt Quick 模块。

这是完整工程文件:

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)
					

Let's walk through the changes we have made. In the find_package 调用,我们替换 核心 with Quick 。这会定位 Qt6Quick 模块并提供 Qt6::Quick 目标,我们稍后链接到。

find_package(Qt6 6.2 COMPONENTS Quick Gui REQUIRED)
					

调用 qt_standard_project_setup , and specify CMAKE_CXX_STANDARD ,和 CMAKE_CXX_STANDARD_REQUIRED . By passing REQUIRES 6.5 to qt_standard_project_setup , we opt-in to useful defaults for qt_add_qml_module .

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 creates and finalizes an application target:

qt_add_executable(myapp
    main.cpp
)
					

qt_add_qml_module passes the target of the executable, a URI, module version, and a list of QML files to ensure that myapp becomes a QML module. This places the QML files into qrc:/qt/qml/${URI} in the resource file system. Moreover, qt_add_qml_module ensures that qmlcachegen runs. Additionally, it creates a myapp_qmllint target, which runs qmllint on the files in QML_FILES.

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

By adding the referenced resources, they get automatically added to the application under the same root path as the QML files – also in the resource file system. By keeping the path in the resource system consistent with the one in the source and build directory, we ensure that the image is always found, as it is resolved relative to FramedImage.qml. It refers to the image in the resource file system if we load main.qml from there, or to the one in the actual file system if we review it with the qml 工具。

target_link_libraries 命令,我们链接到 Qt6::Quick 而不是 Qt6::Core .

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

CMake 快速入门 构建可重用 QML 模块