構建 QML 應用程序

構建 C++ 控製颱應用程序 we showed the CMakeLists.txt file for a simple console application. We will now 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 調用,我們替換 Core 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 . It enables all the Qt CMake 策略 up to version 6.5. In particular QTP0001 that defines a default resource prefix for QML modules, which ensures that they end up under one of the QML engine's default import paths .

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)