Qt5 and CMake

This is a small wrap up on how to get started with Qt5 in a CMake project. For this we will install Qt5 from the Kubuntu 22.04 LTS package manager.

Install Qt5

First we need to install Qt5. You can do this via the installer from the Qt Homepage or use the package manager:

sudo apt install -y qtcreator qtbase5-dev qt5-qmake

CMake – Qt package

For a basic CMake example view my other post on setting up a basic CMake project.
Adding Qt5 to your CMake project is fairly simple and can be achieved with the following CMake lines:

find_package(Qt5 COMPONENTS Core Widgets REQUIRED)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_INCLUDE_CURRENT_DIR ON)

CMake – Qt Targets

The flags we set to ON make our life a lot easier when handling Qt files:

  • CMAKE_AUTOMOC – CMake scans files and invokes Meta-Object Compiler (moc)
  • CMAKE_AUTOUIC – CMake scans files and invokes User-Interface Compiler (uic)
  • CMAKE_AUTORCC – CMake scans files and invokes Resource Compiler (rcc)

CMAKE_INCLUDE_CURRENT_DIR is only required below CMake version 3.7.0 and as the flags suggests adds the current directory to the include directories. This mitigates includes not found files.

All we have to do is add them all with target_sources to our target:

target_sources(MyTarget PRIVATE
    main.cpp
    Application.hpp
    application.ui
    application.qrc
)

Finally we tell Cmake that Qt5 to link the components Core and Widgets with our target:

target_link_libraries(MyTarget PRIVATE Qt5::Core Qt5::Widgets)

This is a small example to quickly get started with Qt5 and CMake. A list of all Qt5 modules can be found here.