mafulechka
mafulechkaApril 23, 2020, 4:56 a.m.

CMake versionless targets (Qt 5.15)

The Qt developers are working on porting Qt 6 to CMake as their internal build system. While Qt 6 is still a few months away, you can already see some of the benefits of this work in Qt 5.15. Christian Adam has already blogged about the improvements in CMake 3.17 and how, for example, AUTOMOC has improved in QT 5.15. This article is about how you can prepare for Qt 6 in your CMake projects.


Looking back: from Qt 4 to Qt 5

While Qt 4 - Qt 5 have been largely source compatible from a C++ perspective, unfortunately this is not the case with the CMake integration itself. Sometimes you had to adapt a large part of the CMake code, in the case of Qt integration.

CMake is now much more commonly used in Qt projects, and CMake support itself has matured significantly. Consequently, the developers do not plan to make any drastic changes to the integration, but instead try to make the transition as smooth as possible.

Problem: versioned targets and commands

One obvious problem is that basically all the CMake APIs (targets, variables, commands) that Qt provides have the major version of Qt in their name. This is true even for very simple examples:

cmake_minimum_required(VERSION 3.5)
project(hellotr LANGUAGES CXX)

find_package(Qt5 COMPONENTS Widgets LinguistTools REQUIRED)
qt5_add_translation(QM_FILES hellotr_en.ts)
add_executable(hellotr
  main.cpp
  ${QM_FILES}
)
target_link_libraries(hellotr Qt5::Widgets)

Now you can argue that, assuming the actual semantics don't change, replacing all calls to Qt5::, qt5_ in your CMake file with Qt6::, qt6_ is easy enough. However, this won't help you if you want to support Qt 5 and Qt 6 for a while.

Versionless targets and commands

So let me introduce the new versionless targets and commands in Qt 5.15. The example above can be written like this:

cmake_minimum_required(VERSION 3.5)
project(hellotr LANGUAGES CXX)

find_package(Qt5 5.15 COMPONENTS Widgets LinguistTools REQUIRED)
qt_add_translation(QM_FILES hellotr_en.ts)
add_executable(hellotr
  main.cpp
  ${QM_FILES}
)
target_link_libraries(hellotr Qt::Widgets)

With the exception of the find_package call, this should work for Qt 6 as well.

If you're interested in the additional 5.15 argument to find_package: this allows CMake to throw an error with the appropriate error message if your version of Qt is older than Qt 5.15.

You can opt out of these new targets and commands by setting the QT_NO_CREATE_VERSIONLESS_TARGETS or QT_NO_CREATE_VERSIONLESS_FUNCTIONS variables before find_package. This is useful, for example, if you have already defined them yourself, or if you still want to access qt_wrap_cpp in Qt 3.

Mixing Qt 5 and Qt 6

Let me start with a big disclaimer: Qt does not support mixing different versions of Qt in the same application! Anyway, there are advanced use cases where you can build separate artifacts using Qt 5 and Qt 6 in the same project.

For these cases, you can set the new variable QT_DEFAULT_MAJOR_VERSION to 5 or 6. If this variable is set before a find_package call that loads Qt 5 or Qt 6, the versionless functions will use the logic from the corresponding Qt version.

Prospects for the future

With the first release of Qt 5.15 approaching, developers will be more and more conservative about the existing CMake framework in this version. In any case, there are plans to further improve the documentation on how it is more productive to use CMake with Qt.

In Qt 6 we will see many more APIs to not only use Qt modules, but also how to define your own Qt modules and plugins.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
ОК

Qt - Test 001. Signals and slots

  • Result:47points,
  • Rating points-6
A
  • Alena
  • Jan. 19, 2025, 11:41 a.m.

C++ - Test 005. Structures and Classes

  • Result:58points,
  • Rating points-2
OI

C++ - Test 001. The first program and data types

  • Result:40points,
  • Rating points-8
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
n
nklyJan. 3, 2025, 2:52 a.m.
Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
M
MarselAug. 16, 2023, 2:26 p.m.
OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks