This page explains how to configure and build existing projects. If you want to know how to create a Qt-based CMake project, see the documentation on how to get started with CMake .
To build a Qt project, CMake needs to know where the Qt installation is located. Usually this is done by setting the CMake variable CMAKE_PREFIX_PATH to Qt's installation prefix. If you are cross-compiling, see 交叉编译 for details on additional variables you will need to set.
If Qt is installed using Qt Online Installer, choose a Qt version within the top-level installation directory. For example, the following command shows how this is done on Windows:
cmake -DCMAKE_PREFIX_PATH=C:\Qt\6.7.2\msvc2019_64 -S <source-dir> -B <build-dir>
The
<source-dir>
and
<build-dir>
placeholders represent the source and build directories of your project.
CMake 生成必要的构建系统文件,使构建工具 (譬如 GNU Make 或 Ninja) 能够构建您的工程。
CMake 的默认生成器从属平台和构建环境。例如在 Windows,CMake 生成 Visual Studio 工程文件若检测到 Visual Studio 环境。
为在所有平台获得一致开发体验,请使用
Ninja
or
Ninja Multi-Config
generator.
You can select the CMake generator either by setting the
CMAKE_GENERATOR
environment variable or using the
-G
自变量:
cmake -G Ninja ...
The
qt-cmake
script is a convenient alternative to configure your project. It eliminates the need for you to specify the
CMAKE_PREFIX_PATH
。可以找到它在
bin
directory of your Qt installation prefix. The script passes all parameters to CMake, so you can use it just like you would use
cmake
:
C:\Qt\6.7.2\msvc2019_64\bin\qt-cmake -G Ninja -S <source-dir> -B <build-dir>
在生成构建系统文件后,工程的构建就绪:
cd <build-dir> ninja
You can also use the generator-independent CMake command:
cmake --build <build-dir>
为异于开发机器的平台构建工程,称为交叉编译。例如在 Windows 机器 (主机平台) 为 Android (目标平台) 构建。
采用 CMake 交叉编译要求 toolchain file for most platforms. It also requires a Qt version for the development host, in addition to a Qt version for the target platform. For example, you need Qt for Windows and Qt for Android installed to cross-compile for Android on Windows.
使用
qt-cmake
from the Qt installation for the target platform, to cross-compile your project for that platform:
<target-qt>/bin/qt-cmake -S <source-dir> -B <build-dir>
This will configure your project for the target platform. The toolchain file is automatically passed, and possibly other platform-specific variables are set up.
The
qt-cmake
script passes a Qt-internal
toolchain file
to CMake. This toolchain file sets several variables that are specific to Qt's target platform.
若正使用的 Qt 安装尚未在您的机器中构建,
qt-cmake
needs to know the location of the CMake toolchain file for the target platform.
在这种情况下,可以指导
qt-cmake
to chainload a custom toolchain file by setting the
QT_CHAINLOAD_TOOLCHAIN_FILE
变量:
~/Qt/6.7.2/android_armv7/bin/qt-cmake -DQT_CHAINLOAD_TOOLCHAIN_FILE=<file-path> -S <source-dir> -B <build-dir>
This instructs Qt's internal toolchain file to load your custom toolchain file as well.
CMake 快速入门 部署