← C++

C++ · 06 / 24

Your first Qt interface with signals and slots

Build a window, react to a button and draw a road element.

  • Medium
  • Intermediate
  • 75 min

Prerequisites: Classes, references, const and RAII, Headers, CMake and first unit tests

In this tutorial
  1. Prepare Qt and CMake
  2. Read the window and drawing surface
  3. Connect an event
  4. Inspect the verification
  5. Build and try it
  6. Exercise and solution
  7. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer, Qt 6.4 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Set CMAKE_PREFIX_PATH to your Qt installation if CMake cannot find Qt. QT_QPA_PLATFORM=offscreen allows verification without a display.

Verified on 2026-10-21 on Linux x86_64. The Qt self-test clicks the button without a display. The solution also checks the updated label.

A graphical application waits for events instead of simply running a console sequence from top to bottom. QApplication manages the event loop. Widgets form the interface and a layout arranges them without hard-coding every screen coordinate.

Qt connects events to reactions through signals and slots. A button emits clicked and a connected operation performs the work. This learning window places road elements using a button. The complete FactoryForge editor later adds mouse coordinates, tools and a separate project model. It intentionally has more responsibilities than this first demonstration.

Package contents and individual files

01Prepare Qt and CMake

Install Qt 6.4 or newer with Widgets. The verified project environment uses Qt 6.8.3. On the existing Linux machine scripts/setup.sh installs tools in the user directory. For your own installation point CMAKE_PREFIX_PATH at its Qt directory. On Windows use matching compiler families for the Qt binaries and your program.

02Read the window and drawing surface

QWidget is the window. QVBoxLayout places the drawing surface and button vertically. QGraphicsScene holds graphical items and QGraphicsView displays them. Local declaration order keeps these objects alive throughout the event loop. This small interface does not save projects yet.

main.cpp · cppOpen file
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
#include <iostream>
int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QWidget window;
  window.setWindowTitle("First warehouse grid");
  QVBoxLayout layout(&window);
  QGraphicsScene scene;
  QGraphicsView view(&scene);
  QPushButton add("Place a road");
  layout.addWidget(&view);
  layout.addWidget(&add);
  int placed = 0;
  QObject::connect(&add, &QPushButton::clicked, &window, [&] {
    scene.addRect(placed * 36, 0, 34, 34, QPen(Qt::NoPen),
                  QBrush(QColor("#23856d")));
    ++placed;
  });
  window.resize(500, 250);
  window.show();
  if (app.arguments().contains("--self-test"))
    QTimer::singleShot(0, &window, [&] {
      add.click();
      std::cout << "tiles=" << placed << '\n';
      app.exit(placed == 1 ? 0 : 1);
    });
  return app.exec();
}

Run / check

cmake -S . -B build -G Ninja
cmake --build build
./build/lesson

03Connect an event

QObject::connect links clicked to a lambda, a small function written where it is needed. [&] accesses existing local variables by reference. Those references remain valid here because the variables live until app.exec finishes. The handler adds a green rectangle and increments placed.

04Inspect the verification

The Qt self-test clicks the button without a display. The solution also checks the updated label.Run python3 run_checks.py from the extracted package. Compare the test expectations with the exercise before opening the solution.

Expected result

The example and automated solution pass. The stated manual checks remain separate.

05Build and try it

Configure with cmake -S . -B build -G Ninja and build with cmake --build build. Run ./build/lesson or build\lesson.exe. Each click on Place a road adds one rectangle. The --self-test option triggers a real button click, checks the result and exits automatically.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(QtGridLesson LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
find_package(Qt6 6.4 REQUIRED COMPONENTS Widgets)
add_executable(lesson main.cpp)
target_link_libraries(lesson PRIVATE Qt6::Widgets)
Expected result

With --self-test the output is tiles=1. Normally each click adds a rectangle.

Your exercise

Change the rectangle color and spacing. Then add a label displaying the number of placed roads.

Show the solution and explanation

QColor supplies the color and placed * 36 determines spacing. Add a QLabel to the layout and set its text after incrementing placed in the handler. Derive the display from the current state. The self-test still verifies that one event creates exactly one road element.

solution/main.cpp · cppOpen file
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QLabel>
#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>
#include <iostream>
int main(int argc, char **argv) {
  QApplication app(argc, argv);
  QWidget window;
  window.setWindowTitle("First warehouse grid");
  QVBoxLayout layout(&window);
  QGraphicsScene scene;
  QGraphicsView view(&scene);
  QPushButton add("Place a road");
  layout.addWidget(&view);
  layout.addWidget(&add);
  QLabel count("0 roads");
  layout.addWidget(&count);
  int placed = 0;
  QObject::connect(&add, &QPushButton::clicked, &window, [&] {
    scene.addRect(placed * 44, 0, 38, 38, QPen(Qt::NoPen),
                  QBrush(QColor("#2954b8")));
    ++placed;
    count.setText(QString::number(placed) + " roads");
  });
  window.resize(500, 250);
  window.show();
  if (app.arguments().contains("--self-test"))
    QTimer::singleShot(0, &window, [&] {
      add.click();
      std::cout << "tiles=" << placed << '\n';
      app.exit(placed == 1 && count.text() == "1 roads" ? 0 : 1);
    });
  return app.exec();
}

Project context and sources

The first six examples are standalone teaching programs. Lessons 7 through 9 use the complete FactoryForge source snapshot. Code, exercises and verified simplifications are explained separately. The project page provides a source ZIP while the GitHub repository is not yet published.