在 CMake 项目中提供 Qt
目前,使 Qt 在用户项目中可用的唯一支持方法是在系统中预装 Qt,或任何可提前构建 Qt 并将其提供给 find_package
如vcpkg
。
当使用 Qt Creator或qt-cmake
( Windows 上为qt-cmake.bat
),Qt 安装位置会自动转发给底层 CMake 调用。
直接使用cmake
时,CMake 使用的一般搜索路径应涵盖大多数 Qt 的非用户安装。要更多地控制使用哪个 Qt 软件包,可以通过https://cmake.org/cmake/help/latest/variable/PackageName_ROOT.html Qt6_ROOT
作为指向 Qt 安装路径的环境变量或缓存变量,或以类似的方式添加或追加到CMAKE_PREFIX_PATH
。例如,如果安装路径是"~/Qt/6.9.1/gcc_64"
,则可在命令行中以-DQt6_ROOT=$HOME/Qt/6.9.1/gcc_64
的形式传递。
注意: 在交叉编译(为其他平台编译,如 WebAssembly 或 Android)和使用 vanillacmake
时,请设置CMAKE_TOOLCHAIN_FILE
,而不是Qt6_ROOT
或CMAKE_PREFIX_PATH
这样的搜索路径。在 Linux 上,工具链文件(针对特定目标平台)通常位于类似下面的路径:"~/Qt/6.9.1/wasm_singlethread/lib/cmake/Qt6/qt.toolchain.cmake"
。它设置了所需的变量,如CMAKE_PREFIX_PATH
、CMAKE_FIND_ROOT_PATH
和QT_HOST_PATH
。
cmake_minimum_required(VERSION 3.16) project(helloworld) find_package(Qt6 REQUIRED)
Qt 软件包分为多个模块,您需要根据项目范围将其包含在内,其中最基本的模块是
find_package(Qt6 REQUIRED COMPONENTS Core)
现代 CMake 支持其他依赖关系提供者,如FetchContent
,但由于 CMake 本身内部紧密集成了 Qt 功能,因此不支持通过FetchContent
使用 Qt。也不支持通过add_subdirectory
和 Git 子模块添加 Qt 源。
注意: 不支持在子目录中调用find_package(Qt6)
,也不支持在function
中调用 。这样做会在不可预测的位置导致各种故障。
相反,应在所有使用 Qt XML 函数的子目录作用域中反复调用find_package(Qt6)
,或将find_package(Qt6)
调用移至根目录CMakeLists.txt
。
© 2025 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.