Skip to content

Test: Qt on the Pi desktop (events, signals and slots)

Qt events

Qt on the Pi Desktop: Events, Signals and Slots

Anatomy of a Qt application, and how it is built

A small Qt Widgets project is a handful of files. main.cpp creates the QApplication and the main window and calls exec(). mainwindow.ui is the form drawn in Qt Creator’s designer; uic turns it into ui_mainwindow.h. Any class with Q_OBJECT (here MainWindow and GpioButton) is read by moc, which writes the code behind its signals and slots. CMakeLists.txt ties these together: qt_standard_project_setup() switches on AUTOMOC and AUTOUIC, so CMake runs moc and uic before the compiler and the linker. Qt Creator opens the same CMakeLists.txt and runs the same steps. Switch parts of the build off and see what breaks, then get it building again.

Challenge: Break the build, then get a clean build of greenhouse.

moc (meta-object compiler)

Reads each class with Q_OBJECT and writes the code behind its signals, slots and properties.

AUTOMOC: CMake runs it for you

uic (user interface compiler)

Turns the designer’s mainwindow.ui into ui_mainwindow.h, which setupUi() uses to build the widgets.

AUTOUIC: CMake runs it for you

CMake and Qt Creator

CMakeLists.txt is the project. Qt Creator opens it, configures a build directory and runs the same build.

cmake -B build && cmake --build build

CMakeLists.txt

the build: targets, Qt modules, libraries

main.cpp

QApplication, the window, exec()

mainwindow.ui

the form (XML), drawn in the designer

mainwindow.h / .cpp

the window class: slots, connections

gpiobutton.h / .cpp

GPIO27 as a Qt event source (step 5)

Configurecmake→ build filesuicAUTOUIC→ ui_mainwindow.hmocAUTOMOC→ moc_*.cppCompileg++→ *.cpp.oLinkld→ greenhouse

Build to see the output here.

← Start here

Result

not built

Highlighted lines follow the switches.

cmake_minimum_required(VERSION 3.16)
project(greenhouse LANGUAGES CXX)
find_package(Qt6 REQUIRED COMPONENTS Widgets)
find_package(PkgConfig REQUIRED)
pkg_check_modules(GPIOD REQUIRED IMPORTED_TARGET libgpiod>=2.0)
qt_standard_project_setup() # turns on AUTOMOC and AUTOUIC
qt_add_executable(greenhouse
main.cpp
mainwindow.h mainwindow.cpp mainwindow.ui
gpiobutton.h gpiobutton.cpp
)
target_link_libraries(greenhouse PRIVATE Qt6::Widgets PkgConfig::GPIOD)

cmake -B build configures once (it finds Qt and libgpiod); cmake --build build then runs moc, uic, the compiler and the linker as needed. Only changed files are rebuilt.