在 CMake 项目中提供 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.12.0/gcc_64" ,则应在命令行中将其作为-DQt6_ROOT=$HOME/Qt/6.12.0/gcc_64 传递。
注意:在进行 交叉编译(为当前平台以外的平台编译,例如 WebAssembly 或 Android)以及使用原生cmake 时,请设置CMAKE_TOOLCHAIN_FILE ,而不是使用Qt6_ROOT 或CMAKE_PREFIX_PATH 等搜索路径。在 Linux 上,工具链文件(特定于某个目标平台)通常位于类似于"~/Qt/6.12.0/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 ,但由于 Qt 功能与 CMake 本身紧密集成,因此不支持通过FetchContent 使用 Qt。通过add_subdirectory 和 Git 子模块添加 Qt 源代码也不受支持。
注意: 在非使用位置的子目录中,或在function 内部调用 find_package(Qt6) 均不被支持。此举可能会在无法预料的位置引发各种错误。
作为替代方案,请在使用 Qt 函数的所有子目录作用域内反复调用find_package(Qt6) ,或者将find_package(Qt6) 的调用移至根目录的CMakeLists.txt 中。
© 2026 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.