Qt5config cmake qt5 config cmake windows

I'm trying to make a very basic Qt5 application using CMake on Windows. I used the documentation of Qt5 to use CMake, and my main.cpp file just contains a main function. My CMakeLists.txt is exact...

I’m trying to make a very basic Qt5 application using CMake on Windows.
I used the documentation of Qt5 to use CMake, and my main.cpp file just contains a main function.

My CMakeLists.txt is exactly:

cmake_minimum_required(VERSION 2.8.9)

project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# Find the QtWidgets library
find_package(Qt5Widgets)

# Tell CMake to create the helloworld executable
add_executable(helloworld hello.cpp)

# Use the Widgets module from Qt 5.
qt5_use_modules(helloworld Widgets)

When in MSysGit bash I enter

$ cmake -G"Visual Studio 11"

I get this output:

$ cmake -G"Visual Studio 11"
-- The C compiler identification is MSVC 17.0.60204.1
-- The CXX compiler identification is MSVC 17.0.60204.1
-- Check for working C compiler using: Visual Studio 11
-- Check for working C compiler using: Visual Studio 11 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler using: Visual Studio 11
-- Check for working CXX compiler using: Visual Studio 11 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMake Warning at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project
  has asked CMake to find a package configuration file provided by
  "Qt5Widgets", but CMake did not find one.

  Could not find a package configuration file provided by "Qt5Widgets" with
  any of the following names:

    Qt5WidgetsConfig.cmake
    qt5widgets-config.cmake

  Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set
  "Qt5Widgets_DIR" to a directory containing one of the above files.  If
  "Qt5Widgets" provides a separate development package or SDK, be sure it has
  been installed.


CMake Error at CMakeLists.txt:17 (qt5_use_modules):
  Unknown CMake command "qt5_use_modules".


-- Configuring incomplete, errors occurred!

Do you have any ideas?

Tsyvarev's user avatar

Tsyvarev

56.7k16 gold badges99 silver badges134 bronze badges

asked Mar 26, 2013 at 14:37

dzada's user avatar

After the lines

cmake_minimum_required(VERSION 2.8.9)

project(testproject)

add

set (CMAKE_PREFIX_PATH "C:\Qt\Qt5.0.1\5.0.1\msvc2010\")

This solves the problem.

Tsyvarev's user avatar

Tsyvarev

56.7k16 gold badges99 silver badges134 bronze badges

answered Mar 27, 2013 at 15:46

dzada's user avatar

dzadadzada

4,9845 gold badges28 silver badges36 bronze badges

8

You should set the CMAKE_PREFIX_PATH environment variable instead or use the cmake-gui to set the path to the Qt 5 packages.

answered Apr 9, 2014 at 18:56

steveire's user avatar

steveiresteveire

10.4k1 gold badge36 silver badges48 bronze badges

1

Here’s a technique that takes advantage of cmake’s ability to read the registry to coerce a registry value into locating the matching msvc’s Qt5Config.cmake.

It attempts to use the highest available Qt5 version by doing a reverse sort on the various «5.x» folder names inside (e.g. C:Qt).

This could be placed inside a module as well, e.g. QtLocator.cmake.

SET(QT_MISSING True)
# msvc only; mingw will need different logic
IF(MSVC)
    # look for user-registry pointing to qtcreator
    GET_FILENAME_COMPONENT(QT_BIN [HKEY_CURRENT_USER\Software\Classes\Applications\QtProject.QtCreator.cpp\shell\Open\Command] PATH)

    # get root path so we can search for 5.3, 5.4, 5.5, etc
    STRING(REPLACE "/Tools" ";" QT_BIN "${QT_BIN}")
    LIST(GET QT_BIN 0 QT_BIN)
    FILE(GLOB QT_VERSIONS "${QT_BIN}/5.*")
    LIST(SORT QT_VERSIONS)

    # assume the latest version will be last alphabetically
    LIST(REVERSE QT_VERSIONS)

    LIST(GET QT_VERSIONS 0 QT_VERSION)

    # fix any double slashes which seem to be common
    STRING(REPLACE "//" "/"  QT_VERSION "${QT_VERSION}")

    # do some math trickery to guess folder
    # - qt uses (e.g.) "msvc2012"
    # - cmake uses (e.g.) "1800"
    # - see also https://cmake.org/cmake/help/v3.0/variable/MSVC_VERSION.html
    MATH(EXPR QT_MSVC "2000 + (${MSVC_VERSION} - 600) / 100")

    # check for 64-bit os
    # may need to be removed for older compilers as it wasn't always offered
    IF(CMAKE_SYSTEM_PROCESSOR MATCHES 64)
        SET(QT_MSVC "${QT_MSVC}_64")
    ENDIF()
    SET(QT_PATH "${QT_VERSION}/msvc${QT_MSVC}")
    SET(QT_MISSING False)
ENDIF()

# use Qt_DIR approach so you can find Qt after cmake has been invoked
IF(NOT QT_MISSING)
    MESSAGE("-- Qt found: ${QT_PATH}")
    SET(Qt5_DIR "${QT_PATH}/lib/cmake/Qt5/")
    SET(Qt5Test_DIR "${QT_PATH}/lib/cmake/Qt5Test")
ENDIF()

And then..

# finally, use Qt5 + COMPONENTS technique, compatible with Qt_DIR
FIND_PACKAGE(Qt5 COMPONENTS Core Gui Widgets Xml REQUIRED)

answered Dec 8, 2017 at 22:39

tresf's user avatar

tresftresf

6,5345 gold badges38 silver badges97 bronze badges

The @tresf’s solution perfectly covers the whole idea. It’s only one thing to add: Microsoft’s versioning seems to be turning into geometric progression. The series is too short yet to confirm, so as of 2019′ the following formula may be used:

# do some math trickery to guess folder
# - qt uses (e.g.) "msvc2012"
# - cmake uses (e.g.) "1800"
# - see also https://cmake.org/cmake/help/v3.0/variable/MSVC_VERSION.html
# - see also https://dev.to/yumetodo/list-of-mscver-and-mscfullver-8nd
if ((MSVC_VERSION GREATER_EQUAL "1920") AND (IS_DIRECTORY "${QT_VERSION}/msvc2019"))
    set(QT_MSVC "2019")
elseif ((MSVC_VERSION GREATER_EQUAL "1910") AND (IS_DIRECTORY "${QT_VERSION}/msvc2017"))
    set(QT_MSVC "2017")
elseif (MSVC_VERSION GREATER_EQUAL "1900")
    set(QT_MSVC "2015")
else ()
    MATH(EXPR QT_MSVC "2000 + (${MSVC_VERSION} - 500) / 100")
endif ()

answered Aug 8, 2019 at 18:56

Dmitry Mikushin's user avatar

One way is to open the CMakeLists.txt in Qt Creator. Qt Creator supports CMake natively and it always knows where Qt is.

answered Sep 19, 2014 at 15:21

user2061057's user avatar

user2061057user2061057

9321 gold badge8 silver badges20 bronze badges

2

image

CMake — это система сборки ПО (точнее генерации файлов управления сборкой), широко используемая с Qt. При создании больших или сложных проектов, выбор CMake будет более предпочтительным, нежели использование qmake. KDE когда-то был переломным моментом в популярности CMake как таковой, после чего свою «лепту» внес Qt 4. В Qt 5 поддержка CMake была значительно улучшена.

Поиск и подключение библиотек Qt 5

Одно из главных изменений при использовании CMake в Qt 5 — это результат увеличенной модульности в самом Qt.

В Qt 4, поиск осуществлялся следующим образом:
find_package (Qt4 COMPONENTS QTCORE QTGUI)

В Qt 5, можно найти все модули, которые Вы хотите использовать, отдельными командами:
find_package (Qt5Widgets)
find_package (Qt5Declarative)
В будущем, возможно, будет способ найти определенные модули в одной команде, но сейчас, в Qt 5, такого вида поиск работать не будет:
find_package(Qt5 COMPONENTS Widgets Declarative)

Сборка проектов Qt 5

После успешного выполнения find_package, пользователям Qt 4 предоставлялась возможность использовать переменные CMake: ${QT_INCLUDES} для установки дополнительных директорий при компиляции и ${QT_LIBRARIES} или ${QT_GUI_LIBRARIES} при линковке.
Так же была возможность использования ${QT_USE_FILE}, для «полуавтоматического» включения необходимых директорий и требуемых define.
С модульной системой Qt 5, переменные теперь будут выглядеть так: ${Qt5Widgets_INCLUDE_DIRS}, ${Qt5Widgets_LIBRARIES}, ${Qt5Declarative_INCLUDE_DIRS}, ${Qt5Declarative_LIBRARIES} и так для каждого используемого модуля.

Это вызывает несовместимость при портировании проекта с Qt 4 в Qt 5. К счастью, это всё легко поправимо.
Сборка в Qt 5 немного сложнее, чем в Qt 4. Одно из различий состоит в том, что в Qt 5 опция configure -reduce-relocations теперь включена по умолчанию. По этой причине, компиляция стала выполняться с опцией -Bsymbolic-functions, которая делает функцию сравнения указателей неэффективной, если не был добавлен флаг -fPIE при сборке исполнимых модулей или -fPIC, при сборке библиотек для позиционно-независимого кода.

Конечно можно сконфигурировать Qt вручную с опцией -no-reduce-relocations и избежать этой проблемы, но возникнут новые проблемы при добавлении компилятору флагов для позиционно-независимого кода, избежать которых можно с помощью CMake:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}")
Это переменная для каждого модуля, доступного в Qt 5, которая будет расширяться для добавления или -fPIE , или пустой строки, в зависимости от того, как Qt был сконфигурирован. Однако флаг -fPIE предназначен только для исполнимых программ и не должен использоваться для библиотек.
Глобальная установка -fPIC, даже при сборке исполнимых модулей не повлечет сбоев, но эта опция не должна быть первой.
set(CMAKE_CXX_FLAGS "-fPIC")

Вкупе с новыми возможностями в CMake, как например автоматический вызов moc, простая система сборки CMake с использованием Qt 5 будет выглядеть примерно так:

CMakeLists

cmake_minimum_required(2.8.7)
project(hello-world)

# Tell CMake to run moc when necessary:
set(CMAKE_AUTOMOC ON)
# As moc files are generated in the binary dir, tell CMake
# to always look for includes there:
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Widgets finds its own dependencies (QtGui and QtCore).
find_package(Qt5Widgets REQUIRED)

# The Qt5Widgets_INCLUDES also includes the include directories for
# dependencies QtCore and QtGui
include_directories(${Qt5Widgets_INCLUDES})

# We need add -DQT_WIDGETS_LIB when using QtWidgets in Qt 5.
add_definitions(${Qt5Widgets_DEFINITIONS})

# Executables fail to build with Qt 5 in the default configuration
# without -fPIE. We add that here.
set(CMAKE_CXX_FLAGS "${Qt5Widgets_EXECUTABLE_COMPILE_FLAGS}")

add_executable(hello_world main.cpp mainwindow.cpp)

# The Qt5Widgets_LIBRARIES variable also includes QtGui and QtCore
target_link_libraries(hello_world ${Qt5Widgets_LIBRARIES})

Навстречу более современному использованию CMake

Начиная с CMake 2.8.8, мы можем немного улучшить предыдущий вариант следующим образом:

CMakeLists

cmake_minimum_required(2.8.8)
project(hello-world)

# Tell CMake to run moc when necessary:
set(CMAKE_AUTOMOC ON)
# As moc files are generated in the binary dir, tell CMake
# to always look for includes there:
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Widgets finds its own dependencies.
find_package(Qt5Widgets REQUIRED)

add_executable(hello_world main.cpp mainwindow.cpp)

qt5_use_modules(hello_world Widgets)

Функция CMake qt5_use_modules инкапсулирует всю установку, необходимую для использования Qt. Она может использоваться с несколькими аргументами сразу для краткости, например:
qt5_use_modules(hello_world Widgets Declarative)
Для qmake это эквивалентно следующему:
TARGET = hello_world
QT += widgets declarative

Все свойства находятся в области видимости конкретной используемой целевой функции, вместо того, чтобы быть в области видимости CMakeLists. Например, в этом фрагменте:

CMakeList

add_executable(hello_world main.cpp mainwindow.cpp)
add_library(hello_library lib.cpp)
add_executable(hello_coretest test.cpp)

find_package(Qt5Widgets)

qt5_use_package(hello_world Widgets)
qt5_use_package(hello_library Core)
qt5_use_package(hello_coretest Test)

т.к. все параметры находятся в области видимости цели (исполняемый модуль или библиотека), с которой они работают, -fPIE не используется при построении библиотеки hello_library и -DQT_GUI_LIB не используется при построении hello_coretest.
Это гораздо более рациональный способ писать систему сборки на CMake.

Детали реализации

Одна из функций CMake, с которой многие разработчики, использовавшие его, знакомы, является Find-файл. Идея состоит в том, чтобы написать Find-файл для каждой зависимости Вашего проекта или использовать уже какой-то существующий Find-файл. CMake сам предоставляет большой набор Find-файлов.
Один из Find-файлов, предоставленных CMake — это файл FindQt4.cmake. Этот файл берет на себя ответственность за поиск Qt в системе, чтобы Вы могли просто вызвать:
find_package(Qt4)

Этот Find-файл делает доступными переменные ${QT_INCLUDES} и ${QT_QTGUI_LIBRARIES}. Одним из недостатков этого файла является то, что он мог устареть. Например, когда вышел Qt 4.6 в декабре 2009, он включал новый модуль QtMultimedia. Поддержки этого модуля не было аж до CMake 2.8.2, вышедшего в июне 2010.

Поиск Qt 5 происходит несколько иначе. Кроме возможности найти зависимости, используя Find-файл, CMake также в состоянии считывает файлы, обеспечивающие зависимости для определения местоположения библиотек и заголовочных файлов. Такие файлы называются файлами конфигурации, и обычно они генерируются самим CMake.

Сборка Qt 5 так же сгенерирует эти конфигурационные файлы CMake, но при этом не появятся зависимости от CMake.
Основное преимущество этого — то, что функции (и модули) Qt, которые могут использоваться с CMake, не будут зависеть от используемой версии CMake. Все модули Qt Essentials и Qt Addons создадут свой собственный файл конфигурации CMake, и функции, предоставляемые модулями, будут сразу доступны через макросы и переменные CMake.

Оригинал статьи: www.kdab.com/using-cmake-with-qt-5

Overview

This document gives an overview of the Qt 6 build system. For a hands-on guide on how
to build Qt 6, see https://doc.qt.io/qt-6/build-sources.html and
https://wiki.qt.io/Building_Qt_6_from_Git

CMake Versions

  • You need CMake 3.16.0 or later for most platforms (due to new AUTOMOC json feature).
  • You need CMake 3.17.0 to build Qt for iOS with the simulator_and_device feature.
  • You need CMake 3.17.0 + Ninja to build Qt in debug_and_release mode on Windows / Linux.
  • You need CMake 3.18.0 + Ninja to build Qt on macOS in debug_and_release mode when using
    frameworks.
  • You need CMake 3.18.0 in user projects that use a static Qt together with QML
    (cmake_language EVAL is required for running the qmlimportscanner deferred finalizer)
  • You need CMake 3.19.0 in user projects to use automatic deferred finalizers
    (automatic calling of qt_finalize_target)
  • You need CMake 3.21.0 in user projects that create user libraries that link against a static Qt
    with a linker that is not capable to resolve circular dependencies between libraries
    (GNU ld, MinGW ld)

Changes to Qt 5

The build system of Qt 5 was done on top of qmake. Qt 6 is built with CMake.

This offered an opportunity to revisit other areas of the build system, too:

  • The Qt 5 build system allowed to build host tools during a cross-compilation run. Qt 6 requires
    you to build a Qt for your host machine first and then use the platform tools from that version. The
    decision to do this was reached independent of cmake: This does save resources on build machines
    as the host tools will only get built once.

  • For now Qt still ships and builds bundled 3rd party code, due to time constraints on getting
    all the necessary pieces together in order to remove the bundled code (changes are necessary
    not only in the build system but in other parts of the SDK like the Qt Installer).

  • There is less need for bootstrapping. Only moc and rcc (plus the lesser known tracegen and
    qfloat16-tables) are linking against the bootstrap Qt library. Everything else can link against
    the full QtCore. This does include qmake.
    qmake is supported as a build system for applications using Qt going forward and will
    not go away anytime soon.

Building against homebrew on macOS

You may use brew to install dependencies needed to build QtBase.

  • Install homebrew:
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
  • Build Qt dependencies: brew install pcre2 harfbuzz freetype
  • Install cmake: brew install cmake
  • When running cmake in qtbase, pass -DFEATURE_pkg_config=ON together with
    -DCMAKE_PREFIX_PATH=/usr/local, or -DCMAKE_PREFIX_PATH=/opt/homebrew if you have a Mac
    with Apple Silicon.

Building

The basic way of building with cmake is as follows:

    cd {build directory}
    cmake -DCMAKE_INSTALL_PREFIX=/path/where/to/install {path to source directory}
    cmake --build .
    cmake --install .

The mapping of configure options to CMake arguments is described here.

You need one build directory per Qt module. The build directory can be a sub-directory inside the
module qtbase/build or an independent directory qtbase_build. The installation prefix is
chosen when running cmake by passing -DCMAKE_INSTALL_PREFIX. To build more than one Qt module,
make sure to pass the same install prefix.

cmake --build and cmake --install are simple wrappers around the basic build tool that CMake
generated a build system for. It works with any supported build backend supported by cmake, but you
can also use the backend build tool directly, e.g. by running make.

CMake has a ninja backend that works quite well and is noticeably faster (and more featureful) than
make, so you may want to use that:

    cd {build directory}
    cmake -GNinja -DCMAKE_INSTALL_PREFIX=/path/where/to/install {path to source directory}
    cmake --build .
    cmake --install .

You can look into the generated build.ninja file if you’re curious and you can also build
targets directly, such as ninja lib/libQt6Core.so.

Make sure to remove CMakeCache.txt if you forgot to set the CMAKE_INSTALL_PREFIX on the first
configuration, otherwise a second re-configuration will not pick up the new install prefix.

You can use cmake-gui {path to build directory} or ccmake {path to build directory} to
configure the values of individual cmake variables or Qt features. After changing a value, you need
to choose the configure step (usually several times:-/), followed by the generate step (to
generate makefiles/ninja files).

Developer Build

When working on Qt itself, it can be tedious to wait for the install step. In that case you want to
use the developer build option, to get as many auto tests enabled and no longer be required to make
install:

    cd {build directory}
    cmake -GNinja -DFEATURE_developer_build=ON {path to source directory}
    cmake --build .
    # do NOT make install

Specifying configure.json features on the command line

QMake defines most features in configure.json files, like -developer-build or -no-opengl.

In CMake land, we currently generate configure.cmake files from the configure.json files into
the source directory next to them using the helper script
path_to_qtbase_source/util/cmake/configurejson2cmake.py. They are checked into the repository.
If the feature in configure.json has the name «dlopen», you can specify whether to enable or disable that
feature in CMake with a -D flag on the CMake command line. So for example -DFEATURE_dlopen=ON or
-DFEATURE_sql_mysql=OFF. Remember to convert all ‘-‘ to ‘_’ in the feature name.
At the moment, if you change a FEATURE flag’s value, you have to remove the
CMakeCache.txt file and reconfigure with CMake. And even then you might stumble on some issues when
reusing an existing build, because of an automoc bug in upstream CMake.

Building with CCache

You can pass -DQT_USE_CCACHE=ON to make the build system look for ccache in your PATH
and prepend it to all C/C++/Objective-C compiler calls. At the moment this is only supported for the
Ninja and the Makefile generators.

Cross Compiling

Compiling for a target architecture that’s different than the host requires one build of Qt for the
host. This «host build» is needed because the process of building Qt involves the compilation of
intermediate code generator tools, that in turn are called to produce source code that needs to be
compiled into the final libraries. These tools are built using Qt itself and they need to run on the
machine you’re building on, regardless of the architecture you are targeting.

Build Qt regularly for your host system and install it into a directory of your choice using the
CMAKE_INSTALL_PREFIX variable. You are free to disable the build of tests and examples by
passing -DQT_BUILD_EXAMPLES=OFF and -DQT_BUILD_TESTS=OFF.

With this installation of Qt in place, which contains all tools needed, we can proceed to create a
new build of Qt that is cross-compiled to the target architecture of choice. You may proceed by
setting up your environment. The CMake wiki has further information how to do that at

https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/CrossCompiling

Yocto based device SDKs come with an environment setup script that needs to be sourced in your shell
and takes care of setting up environment variables and a cmake alias with a toolchain file, so that
you can call cmake as you always do.

In order to make sure that Qt picks up the code generator tools from the host build, you need to
pass an extra parameter to cmake:

    -DQT_HOST_PATH=/path/to/your/host_build

The specified path needs to point to a directory that contains an installed host build of Qt.

Cross Compiling for Android

In order to cross-compile Qt to Android, you need a host build (see instructions above) and an
Android build. In addition, it is necessary to install the Android NDK.

The following CMake variables are required for an Android build:

  • ANDROID_SDK_ROOT must point to where the Android SDK is installed
  • CMAKE_TOOLCHAIN_FILE must point to the toolchain file that comes with the NDK
  • QT_HOST_PATH must point to a host installation of Qt

Call CMake with the following arguments:
-DCMAKE_TOOLCHAIN_FILE=<path/to/ndk>/build/cmake/android.toolchain.cmake -DQT_HOST_PATH=/path/to/your/host/build -DANDROID_SDK_ROOT=<path/to/sdk> -DCMAKE_INSTALL_PREFIX=$INSTALL_PATH

The toolchain file is usually located below the NDK’s root at «build/cmake/android.toolchain.cmake».
Instead of specifying the toolchain file you may specify ANDROID_NDK_ROOT instead.
This variable is exclusively used for auto-detecting the toolchain file.

In a recent SDK installation, the NDK is located in a subdirectory «ndk_bundle» below the SDK’s root
directory. In that situation you may omit ANDROID_NDK_ROOT and CMAKE_TOOLCHAIN_FILE.

If you don’t supply the configuration argument -DANDROID_ABI=..., it will default to
armeabi-v7a. To target other architectures, use one of the following values:

  • arm64: -DANDROID_ABI=arm64-v8a
  • x86: -DANDROID_ABI=x86
  • x86_64: -DANDROID_ABI=x86_64

By default we set the android API level to 23. Should you need to change this supply the following
configuration argument to the above CMake call: -DANDROID_PLATFORM=android-${API_LEVEL}.

Cross compiling for iOS

In order to cross-compile Qt to iOS, you need a host macOS build.

When running cmake in qtbase, pass
-DCMAKE_SYSTEM_NAME=iOS -DQT_HOST_PATH=/path/to/your/host/build -DCMAKE_INSTALL_PREFIX=$INSTALL_PATH

If you don’t supply the configuration argument -DQT_UIKIT_SDK=..., CMake will build a
multi-arch simulator_and_device iOS build.
To target another SDK / device type, use one of the following values:

  • iphonesimulator: -DQT_UIKIT_SDK=iphonesimulator
  • iphoneos: -DQT_UIKIT_SDK=iphoneos

Depending on what value you pass to -DQT_UIKIT_SDK= a list of target architectures is chosen
by default:

  • iphonesimulator: x86_64
  • iphoneos: arm64
  • simulator_and_device: arm64;x86_64

You can try choosing a different list of architectures by passing
-DCMAKE_OSX_ARCHITECTURES=x86_64;i386.
Note that if you choose different architectures compared to the default ones, the build might fail.
Only do it if you know what you are doing.

Debugging CMake files

CMake allows specifying the --trace and --trace-expand options, which work like
qmake -d -d: As the cmake code is evaluated, the values of parameters and variables is shown.
This can be a lot of output, so you may want to redirect it to a file using the
--trace-redirect=log.txt option.

Porting Help

We have some python scripts to help with the conversion from qmake to cmake. These scripts can be
found in utils/cmake.

configurejson2cmake.py

This script converts all configure.json in the Qt repository to configure.cmake files for
use with CMake. We want to generate configure.cmake files for the foreseeable future, so if you need
to tweak the generated configure.cmake files, please tweak the generation script instead.

configurejson2cmake.py is run like this: util/cmake/configurejson2cmake.py . in the
top-level source directory of a Qt repository.

pro2cmake.py

pro2cmake.py generates a skeleton CMakeLists.txt file from a .pro-file. You will need to polish
the resulting CMakeLists.txt file, but e.g. the list of files, etc. should be extracted for you.

pro2cmake.py is run like this: path_to_qtbase_source/util/cmake/pro2cmake.py some.pro.

run_pro2cmake.py

« A small helper script to run pro2cmake.py on all .pro-files in a directory. Very useful to e.g.
convert all the unit tests for a Qt module over to cmake;-)

run_pro2cmake.py is run like this: path_to_qtbase_source/util/cmake/run_pro2cmake.py some_dir.

vcpkg support

The initial port used vcpkg to provide 3rd party packages that Qt requires.

At the moment the Qt CI does not use vcpkg anymore, and instead builds bundled 3rd party sources
if no relevant system package is found.

While the supporting code for building with vcpkg is still there, it is not tested at this time.

How to convert certain constructs

qmake CMake
qtHaveModule(foo) if(TARGET Qt::foo)
qtConfig(foo) if (QT_FEATURE_foo)

Convenience Scripts

A Qt installation’s bin directory contains a number of convenience scripts.

qt-cmake

This is a wrapper around the CMake executable which passes a Qt-internal CMAKE_TOOLCHAIN_FILE. Use
this to build projects against the installed Qt.

To use a custom toolchain file, use -DQT_CHAINLOAD_TOOLCHAIN_FILE=<file path>.

qt-cmake-private

The same as qt-cmake, but in addition, sets the CMake generator to Ninja.

Example:

$ cd some/empty/directory
$ ~/Qt/6.0.0/bin/qt-cmake-private ~/source/of/qtdeclarative -DFEATURE_qml_network=OFF
$ cmake --build . && cmake --install .

qt-configure-module

Call the configure script for a single Qt module, doing a CMake build.

Example:

$ cd some/empty/directory
$ ~/Qt/6.0.0/bin/qt-configure-module ~/source/of/qtdeclarative -no-feature-qml-network
$ cmake --build . && cmake --install .

qt-cmake-standalone-test

Build a single standalone test outside the Qt build.

Example:

$ cd some/empty/directory
$ ~/Qt/6.0.0/bin/qt-cmake-standalone-test ~/source/of/qtbase/test/auto/corelib/io/qprocess
$ cmake --build .

I work on build systems a fair bit, and this is something I thought others might benefit from. I went through quite a bit of code in our projects that did not do things the “right way”, and it wasn’t clear what that was to me at first. Qt 5 improved its integration with CMake quite significantly – moving from using the qmake command to find Qt 4 components in a traditional CMake find module to providing its own CMake config files. This meant that instead of having to guess where Qt and its libraries/headers were installed we could use the information generated by Qt’s own build system. This led to many of us, myself included, finding Qt 5 modules individually:

find_package(Qt5Core REQUIRED)
find_package(Qt5Widgets REQUIRED)

This didn’t feel right to me, but I hadn’t yet seen what I think is the preferred way (and the way I would recommend) to find Qt 5. It also led to either using ‘CMAKE_PREFIX_PATH’ to specify the prefix Qt 5 was installed in, or passing in ‘Qt5Core_DIR’, ‘Qt5Widgets_DIR’, etc for the directory containing each and every Qt 5 config module – normally all within a common prefix. There is a better way, and it makes many of these things simpler again:

find_package(Qt5 COMPONENTS Core Widgets REQUIRED)

This is not only more compact, which is always nice, but it means that you can simply pass in ‘Qt5_DIR’ to your project, and it will use that when searching for the components. There are many other great features in CMake that improve Qt integration, but I want to keep this post short…

CMake is a tool that helps simplify the build process for development projects across different platforms. CMake automates the generation of buildsystems such as Makefiles and Visual Studio project
files.

CMake is a 3rd party tool with its own documentation. The rest of this manual details the specifics of how to use Qt 5 with CMake.
The minimum version required to use Qt5 is CMake 3.1.0.

Getting Started

The first requirement when using CMake is to use find_package to locate the libraries and header files shipped with Qt. These libraries and header files can then be used to build libraries and
applications based on Qt.

The recommended way to use Qt libraries and headers with CMake is to use the target_link_libraries command. This command automatically adds appropriate include directories, compile definitions, the
position-independent-code flag, and links to the qtmain.lib library on Windows.

To build a helloworld GUI executable, typical usage would be:

cmake_minimum_required(VERSION 3.1.0)

project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed
set(CMAKE_AUTOMOC ON)
# Create code from a list of Qt designer ui files
set(CMAKE_AUTOUIC ON)

# Find the QtWidgets library
find_package(Qt5Widgets CONFIG REQUIRED)

# Populate a CMake variable with the sources
set(helloworld_SRCS
    mainwindow.ui
    mainwindow.cpp
    main.cpp
)
# Tell CMake to create the helloworld executable
add_executable(helloworld WIN32 ${helloworld_SRCS})
# Use the Widgets module from Qt 5
target_link_libraries(helloworld Qt5::Widgets)

In order for find_package to be successful, Qt 5 must be found below the CMAKE_PREFIX_PATH, or the Qt5<Module>_DIR must be set in the CMake cache to the location of the Qt5WidgetsConfig.cmake
file. The easiest way to use CMake is to set the CMAKE_PREFIX_PATH environment variable to the install prefix of Qt 5.

The CMAKE_AUTOMOC setting runs moc automatically when required. For more on this feature see the CMake AUTOMOC documentation

Imported targets

Imported targets are created for each Qt module. Imported target names should be preferred instead of using a variable like Qt5<Module>_LIBRARIES in CMake commands
such as target_link_libraries. The actual path to the library can be obtained using the LOCATION property:

find_package(Qt5Core)

get_target_property(QtCore_location Qt5::Core LOCATION)

Note however that it is rare to require the full location to the library in CMake code. Most CMake APIs are aware of imported targets and can automatically use them instead of the full path.

Each module in Qt 5 has a library target with the naming convention Qt5::<Module> which can be used for this purpose.

Imported targets are created with the configurations Qt was configured with. That is, if Qt was configured with the -debug switch, an imported target with the configuration DEBUG will be created. If Qt was configured with
the -release switch an imported target with the configuration RELEASE will be created. If Qt was configured with the -debug-and-release switch (the default on windows), then imported targets will be created with both RELEASE
and DEBUG configurations.

If your project has custom CMake build configurations, it may be necessary to set a mapping from your custom configuration to either the debug or release Qt configuration.

find_package(Qt5Core)

set(CMAKE_CXX_FLAGS_COVERAGE "${CMAKE_CXX_FLAGS_RELEASE} -fprofile-arcs -ftest-coverage")

# set up a mapping so that the Release configuration for the Qt imported target is
# used in the COVERAGE CMake configuration.
set_target_properties(Qt5::Core PROPERTIES MAP_IMPORTED_CONFIG_COVERAGE "RELEASE")

Plugins are also available as IMPORTED targets in CMake. The Qt Network, Qt SQL, Qt GUI, and Qt Widgets modules have plugins associated. They provide a list of plugins in the Qt5<Module>_PLUGINS variable.

foreach(plugin ${Qt5Network_PLUGINS})
  get_target_property(_loc ${plugin} LOCATION)
  message("Plugin ${plugin} is at location ${_loc}")
endforeach()

Variable Reference

Module variables

The result of a find_package call is that imported targets will be created for use with target_link_libraries, some variables will be populated with information required to configure the build, and
macros will be made available for use. The name of the imported target for each module matches the name of the module with a prefix of ‘Qt5::’, for example Qt5::Widgets. All of the package-specific variables have a consistent
name with a prefix of the name of the package. For example, find_package(Qt5Widgets) will make the following variables available if successfully found:

  • Qt5Widgets_VERSION String describing the version of the module.
  • Qt5Widgets_LIBRARIES List of libraries for use with the target_link_libraries command.
  • Qt5Widgets_INCLUDE_DIRS List of directories for use with the include_directories command.
  • Qt5Widgets_DEFINITIONS List of definitions for use with add_definitions.
  • Qt5Widgets_COMPILE_DEFINITIONS List of definitions for use with the COMPILE_DEFINITIONS target property.
  • Qt5Widgets_FOUND Boolean describing whether the module was found successfully.
  • Qt5Widgets_EXECUTABLE_COMPILE_FLAGS String of flags to be used when building executables.

Equivalents of those variables will be available for all packages found with a find_package call. Note that the variables are case-sensitive.

Installation variables

Additionally, several other variables are available which do not relate to a particular package, but to the Qt installation itself.

  • QT_VISIBILITY_AVAILABLE Boolean describing whether Qt was built with hidden visibility.
  • QT_LIBINFIX String containing the infix used in library names.

Macro Reference

Qt5Core macros

Macros available when Qt5Core is found.

Macro Description
qt5_wrap_cpp(outfiles inputfile … OPTIONS …) Create moc code from a list of files containing Qt class with the Q_OBJECT declaration. Per-directory preprocessor definitions are also added. Options may be given to moc, such as
those found when executing «moc -help».
qt5_add_resources(outfiles inputfile … OPTIONS …) Create code from a list of Qt resource files. Options may be given to rcc, such as those found when executing «rcc -help».
qt5_add_binary_resources(target inputfile … OPTIONS … DESTINATION …) Create an RCC file from a list of Qt resource files. Options may be given to rcc, such as those found when executing «rcc -help». A destination may be given to use a different filename or path for the RCC file.
qt5_generate_moc(inputfile outputfile ) Creates a rule to run moc on infile and create outfile. Use this if for some reason QT5_WRAP_CPP() isn’t appropriate, e.g. because you need a custom filename for the moc file or something similar.
qt5_use_modules(target [LINK_PUBLIC|LINK_PRIVATE] module … ) Indicates that the target uses the named Qt 5 modules. The target will be linked to the specified modules, use the include directories installed by those modules, use the COMPILE_DEFINITIONS set by those modules, and
use the COMPILE_FLAGS set by the modules. The LINK_PRIVATE or LINK_PUBLIC specifiers can optionally be specified. If LINK_PRIVATE is specified then the modules are not made part of the link interface of the target. See
the documentation for target_link_libraries for more information.

Note that this macro is only available if using CMake 2.8.9 or later. This macro is obsolete. Use target_link_libraries with IMPORTED targets instead.

Qt5Widgets macros

Macros available when Qt5Widgets is found.

Macro Description
qt5_wrap_ui(outfiles inputfile … OPTIONS …) Create code from a list of Qt designer ui files. Options may be given to uic, such as those found when executing «uic -help»

Qt5DBus macros

Macros available when Qt5DBus is found.

Macro Description
qt5_add_dbus_interface(outfiles interface basename) Create the interface header and implementation files with the given basename from the given interface xml file and add it to the list of sources
qt5_add_dbus_interfaces(outfiles inputfile … ) Create the interface header and implementation files for all listed interface xml files the name will be automatically determined from the name of the xml file
qt5_add_dbus_adaptor(outfiles xmlfile parentheader parentclassname [basename] [classname]) Create a dbus adaptor (header and implementation file) from the xml file describing the interface, and add it to the list of sources. The adaptor forwards the calls to a parent class, defined in parentheader and named
parentclassname. The name of the generated files will be <basename>adaptor.{cpp,h} where basename defaults to the basename of the xml file. If <classname> is provided, then it will be used as the classname of
the adaptor itself.
qt5_generate_dbus_interface( header [interfacename] OPTIONS …) Generate the xml interface file from the given header. If the optional argument interfacename is omitted, the name of the interface file is constructed from the basename of the header with the suffix .xml appended.
Options may be given to qdbuscpp2xml, such as those found when executing «qdbuscpp2xml —help»

Qt5LinguistTools macros

Macros available when Qt5LinguistTools is found.

Macro Description
qt5_create_translation( qm_files directories … sources … ts_files … OPTIONS …) Out: qm_files In: Directories sources ts_files Options: flags to pass to lupdate, such as -extensions to specify Extensions for a directory scan. Generates commands to create .ts (via lupdate) and .qm (via lrelease) —
files from directories and/or sources. The ts files are created and/or updated in the source tree (unless given with full paths). The qm files are generated in the build tree. Updating the translations can be done by
adding the qm_files to the source list of your library/executable, so they are always updated, or by adding a custom target to control when they get updated/generated.
qt5_add_translation( qm_files ts_files … ) Out: qm_files In: ts_files Generates commands to create .qm from .ts — files. The generated filenames can be found in qm_files. The ts_files must exist and are not updated in any way.

  1. 1. Configure the IDE CLion
  2. 2. CMakeLists.txt
  3. 3. main.cpp

Write

«Hello, World !!!»

On Qt in the

IDE CLion

using the

CMAKE

build system. The emphasis on the fact that the project is being developed in IDE CLion was made because to work with the project it is necessary to make a small adjustment for working with

CMAKE

.

The result is the following application:


Configure the IDE CLion

After you create the project, you need to configure it to work with the Qt library, you need to configure the path to this library through the argument CMAKE_PREFIX_PATH.

To do this, go to the IDE settings.

File -> Settings -> Build, Execution, Deployment -> CMake

Further in CMake Options through

CMAKE_PREFIX_PATH

we specify a way to libraries Qt for

CMAKE

. The full path to the libraries can be:

/home/user/Qt/5.9.1/gcc_64/lib/cmake

The entire prefix record will be as follows:

-DCMAKE_PREFIX_PATH=/home/user/Qt/5.9.1/gcc_64/lib/cmake

In the settings, this window will look like this.

CMakeLists.txt

In CMakeLists.txt, in addition to the information added by default, you will need to add the search and connect Qt libraries by using the

find_package

and

target_link_libraries

functions.

cmake_minimum_required(VERSION 3.8)
project(HelloWorld)

set(CMAKE_CXX_STANDARD 17)

# Include a library search using find_package() 
# via REQUIRED, specify that libraries are required
find_package(Qt5Core REQUIRED)
find_package(Qt5Gui REQUIRED)
find_package(Qt5Widgets REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(HelloWorld ${SOURCE_FILES})

# specify which libraries to connect
target_link_libraries(${PROJECT_NAME} Qt5::Core)
target_link_libraries(${PROJECT_NAME} Qt5::Gui)
target_link_libraries(${PROJECT_NAME} Qt5::Widgets)

main.cpp

Otherwise, writing the first HelloWorld will be a similar development under Qt Creator.

#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QLabel>

int main(int argc, char *argv[]) {

    QApplication app(argc, argv);

    QWidget widget;
    widget.resize(640, 480);
    widget.setWindowTitle("Hello, world!!!");

    QGridLayout *gridLayout = new QGridLayout(&widget);

    QLabel * label = new QLabel("Hello, world!!!");
    label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
    gridLayout->addWidget(label);

    widget.show();

    return app.exec();
}

When developing under Qt Creator using the CMake build system, I did not like the fact that when you add files to a project, Qt Creator does not register them in CMakeLists.txt, that is, files are created but not included in the project. It also has a number of minor inconveniences, although IDE CLion is still far from convenient in working with very specific Qt functionality, at least take the auto-completion of Qt macros, automatically create the missing class members (variables and methods) for these macros, work with the designer, etc. .

Понравилась статья? Поделить с друзьями:
  • Qt5concurrent dll скачать 64 bit windows 10
  • Qt5charts dll скачать 64 bit windows 10
  • Qt5 библиотека скачать 64 bit windows 10
  • Qt windows не удалось запустить программу путь или права недопустимы
  • Qt qpa plugin could not find the qt platform plugin windows