Building a QML application | Build with CMake | Qt 6.11.2

- Qt 6.11
- Build with CMake
- Building a QML application
- Qt 6.11.2 Reference Documentation

Getting started with CMake ◦ Building a reusable QML module

# Building a QML application

In Building a C++ console application, we showed the CMakeLists.txt file for a simple console application. We will now create a QML application that uses the Qt Quick module.

Here is the full project file:

     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)

Let's walk through the changes we have made, compared to the console application `CMakeLists.txt`:

         ...
     find_package(Qt6 6.5 COMPONENTS Quick REQUIRED)

In the `find_package()` call, we replace `Core` with `Quick`. CMake will therefore load the `Qt6Quick` module and provide the `Qt6::Quick` targets we later link against. CMake will also automatically load packages Quick depends on, like `Qt6Qml`, which defines the qt_add_qml_module() command we use below.

We also require Qt 6.5 or newer.

     qt_standard_project_setup(REQUIRES 6.5)

The qt_standard_project_setup() command sets project-wide defaults for a typical Qt application. By adding `REQUIRES 6.5`, we enable the policy QTP0001, which defines a default resource prefix for QML modules created by qt_add_qml_module().

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

qt_add_qml_module() adds a QML module named `hello` to the executable, consisting of two QML files and one image. Due to QTP0001, the module will be available at `qrc:/qt/qml/hello` in the resource file system, with `qrc:/qt/qml/` being one of the QML engine's default import paths.

qt_add_qml_module() also does optimization steps like running the QML script compiler, and defining a `helloworld_qmllint` target which you can run to get additional suggestions about the `.qml` files from qmllint.

     target_link_libraries(helloworld PRIVATE Qt6::Quick)

In the `target_link_libraries()` command, we link our executable against `Qt6::Quick`. This automatically also links against targets `Qt6::Quick` depends on, including `Qt6::Qml` and `Qt6::Core`.

Getting started with CMake ◦ Building a reusable QML module