← C++

C++ · 23 / 24

Test Qt interfaces through actions and signals

Verify inputs, table and application service working together through reproducible widget tests.

  • Large
  • Advanced
  • 90 min

Prerequisites: Qt model/view with sorting, filtering and editing, Asynchronous HTTP requests with cancellation and deadlines, Persist orders with SQLite and transactions

In this tutorial
  1. Build a testable interface
  2. Interact with the demo
  3. Exercise user actions
  4. Connect signals with domain outcomes
  5. Check keyboard interaction
  6. Understand automated UI test limits
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20, CMake 3.25 or later, CTest and Python 3. Qt 6.8 with Core, Widgets and Test. Set CMAKE_PREFIX_PATH to your Qt installation if it is not discovered automatically. Locally checked with Qt 6.8.3. Extract the ZIP into a new folder. python3 run_checks.py checks example and solution in a temporary copy and preserves your files. Run python3 verify.py for your own build. The demo is then available at build/order_lab. Qt demos use English labels. Automated widget tests default to offscreen. Run the visible demo in a desktop session without QT_QPA_PLATFORM=offscreen. Native Windows execution is not verified.

Verified on 2026-10-21 on Linux x86_64. Real Qt widgets, invalid input, keyboard input, saving, sorted selection, deletion, filtering and a focus shortcut. Linux offscreen, without native Windows or screen-reader acceptance testing.

A passing core test does not establish that a button deletes the correct order or displays an input error. This tutorial drives real Qt widgets using QTest. Tests inspect both visible outcomes and stored state. A keyboard exercise adds a verifiable focus change.

Package contents and individual files

01Build a testable interface

Widgets receive stable objectName values such as title, save and orders. Tests can locate them without depending on screen coordinates or translated labels. The form saves through OrderService. Invalid input displays a message and preserves table data.

order_editor.hpp · cppOpen file
#pragma once
#include "order_model.hpp"
#include <QCheckBox>
#include <QFormLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSpinBox>
#include <QTableView>
#include <QVBoxLayout>

namespace orders {
class OrderEditor : public QWidget {
  OrderService &service_;
  OrderModel model_;
  OpenFilter proxy_;
  QSpinBox *id_;
  QLineEdit *title_;
  QSpinBox *priority_;
  QCheckBox *done_;
  QTableView *table_;
  QLabel *message_;

public:
  explicit OrderEditor(OrderService &service, QWidget *parent = nullptr)
      : QWidget(parent), service_(service), model_(service, this),
        proxy_(this) {
    auto *layout = new QVBoxLayout(this);
    auto *search = new QLineEdit(this);
    search->setObjectName("search");
    search->setPlaceholderText("Filter titles");
    search->setAccessibleName("Filter titles");
    auto *onlyOpen = new QCheckBox("Open orders only", this);
    onlyOpen->setObjectName("onlyOpen");
    layout->addWidget(search);
    layout->addWidget(onlyOpen);
    proxy_.setSourceModel(&model_);
    table_ = new QTableView(this);
    table_->setObjectName("orders");
    table_->setModel(&proxy_);
    table_->setSortingEnabled(true);
    table_->sortByColumn(0, Qt::AscendingOrder);
    table_->setSelectionBehavior(QAbstractItemView::SelectRows);
    table_->setSelectionMode(QAbstractItemView::SingleSelection);
    table_->setEditTriggers(QAbstractItemView::NoEditTriggers);
    table_->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    layout->addWidget(table_);
    auto *form = new QFormLayout;
    id_ = new QSpinBox(this);
    id_->setObjectName("id");
    id_->setRange(1, 1000000);
    title_ = new QLineEdit(this);
    title_->setObjectName("title");
    priority_ = new QSpinBox(this);
    priority_->setObjectName("priority");
    priority_->setRange(0, 2);
    done_ = new QCheckBox("Done", this);
    done_->setObjectName("done");
    form->addRow("ID", id_);
    form->addRow("Title", title_);
    form->addRow("Priority", priority_);
    form->addRow("Status", done_);
    layout->addLayout(form);
    auto *buttons = new QHBoxLayout;
    auto *save = new QPushButton("Save order", this);
    save->setObjectName("save");
    auto *remove = new QPushButton("Delete selected", this);
    remove->setObjectName("remove");
    buttons->addWidget(save);
    buttons->addWidget(remove);
    layout->addLayout(buttons);
    message_ = new QLabel(this);
    message_->setObjectName("message");
    message_->setWordWrap(true);
    layout->addWidget(message_);
    connect(search, &QLineEdit::textChanged, &proxy_,
            &QSortFilterProxyModel::setFilterFixedString);
    connect(onlyOpen, &QCheckBox::toggled, this,
            [this](bool value) { proxy_.setOnlyOpen(value); });
    connect(table_->selectionModel(), &QItemSelectionModel::currentRowChanged,
            this, [this](const QModelIndex &current) {
              if (!current.isValid())
                return;
              auto source = proxy_.mapToSource(current);
              id_->setValue(source.data(OrderModel::Id).toInt());
              title_->setText(model_.index(source.row(), 1).data().toString());
              priority_->setValue(source.data(OrderModel::Priority).toInt());
              done_->setChecked(!source.data(OrderModel::Open).toBool());
            });
    connect(save, &QPushButton::clicked, this, [this] {
      auto result = service_.save(
          {id_->value(), title_->text().toStdString(), priority_->value(),
           done_->isChecked() ? Status::done : Status::open});
      if (report(result, "Saved"))
        refresh();
    });
    connect(remove, &QPushButton::clicked, this, [this] {
      const auto current = table_->currentIndex();
      if (!current.isValid()) {
        message_->setText("Select an order first");
        return;
      }
      const auto source = proxy_.mapToSource(current);
      auto result = service_.remove(source.data(OrderModel::Id).toInt());
      if (report(result, "Deleted"))
        refresh();
    });
    refresh();
  }
  bool report(const Result<Done> &result, const QString &success) {
    if (!succeeded(result)) {
      message_->setText(
          QString::fromStdString(std::get<Error>(result).message));
      return false;
    }
    message_->setText(success);
    return true;
  }
  void refresh() {
    auto loaded = model_.refresh();
    if (!succeeded(loaded))
      report(loaded, {});
  }
};
} // namespace orders
Expected result

An empty title produces a visible error message.

02Interact with the demo

Run ./build/order_lab in a desktop session. Enter an unused ID and a title, then click Save order. Select a row to edit its values. Reusing an ID deliberately updates that order. The example UI uses English labels and stores data in memory at this stage.

main.cpp · cppOpen file
#include "order_editor.hpp"
#include "test_support.hpp"
#include <QApplication>
int main(int argc, char **argv) {
  QApplication app(argc, argv);
  orders::MemoryRepository repository;
  orders::OrderService service(repository);
  service.replace(samples());
  orders::OrderEditor editor(service);
  editor.setWindowTitle("Order model · memory example");
  editor.resize(720, 520);
  editor.show();
  return app.exec();
}
Expected result

A new order appears immediately in the table.

03Exercise user actions

The test first clicks Save order with an empty title. It then types a title using QTest::keyClicks and saves again. It sorts descending, selects the new record in the visible table and deletes it through the actual button. Exactly the original orders must remain afterward.

tests.cpp · cppOpen file
#include "order_editor.hpp"
#include "test_support.hpp"
#include <QtTest>
using namespace orders;
class UiTests : public QObject {
  Q_OBJECT
private slots:
  void saveValidateFilterAndDelete() {
    MemoryRepository repository;
    OrderService service(repository);
    QVERIFY(succeeded(service.replace(samples())));
    OrderEditor editor(service);
    editor.resize(700, 480);
    editor.show();
    auto *title = editor.findChild<QLineEdit *>("title");
    auto *id = editor.findChild<QSpinBox *>("id");
    auto *table = editor.findChild<QTableView *>("orders");
    auto *save = editor.findChild<QPushButton *>("save");
    id->setValue(4);
    QTest::mouseClick(save, Qt::LeftButton);
    QCOMPARE(table->model()->rowCount(), 3);
    QVERIFY(editor.findChild<QLabel *>("message")->text().contains("title"));
    title->setFocus();
    QTest::keyClicks(title, "Added by keyboard");
    QTest::mouseClick(save, Qt::LeftButton);
    QCOMPARE(table->model()->rowCount(), 4);
    QVERIFY(std::get<std::vector<Order>>(service.list()).back().title ==
            "Added by keyboard");
    table->sortByColumn(0, Qt::DescendingOrder);
    auto index = table->model()->index(0, 0);
    QCOMPARE(index.data(OrderModel::Id).toInt(), 4);
    QTest::mouseClick(table->viewport(), Qt::LeftButton, {},
                      table->visualRect(index).center());
    QTest::mouseClick(editor.findChild<QPushButton *>("remove"),
                      Qt::LeftButton);
    QVERIFY(std::get<std::vector<Order>>(service.list()) == samples());
    auto *checkbox = editor.findChild<QCheckBox *>("onlyOpen");
    QTest::mouseClick(checkbox, Qt::LeftButton, {},
                      QPoint(8, checkbox->height() / 2));
    QCOMPARE(table->model()->rowCount(), 2);
    editor.findChild<QLineEdit *>("search")->setText("motors");
    QCOMPARE(table->model()->rowCount(), 1);
  }
};
QTEST_MAIN(UiTests)
#include "tests.moc"
Expected result

Invalid input changes nothing. Creating and deleting restore the original batch.

04Connect signals with domain outcomes

The model emits dataChanged only after successful persistence. Tutorial 19 checks this signal with QSignalSpy. Here we check the widget wiring above it. Visible row counts alone would be too weak, so deletion also compares the actual stored orders.

order_model.hpp · cppOpen file
#pragma once
#include "repository.hpp"
#include <QAbstractTableModel>
#include <QSortFilterProxyModel>

namespace orders {
class OrderModel final : public QAbstractTableModel {
  OrderService &service_;
  std::vector<Order> values_;
  QString lastError_;

public:
  enum Role { Id = Qt::UserRole + 1, Priority, Open };
  explicit OrderModel(OrderService &service, QObject *parent = nullptr)
      : QAbstractTableModel(parent), service_(service) {}
  int rowCount(const QModelIndex &parent = {}) const override {
    return parent.isValid() ? 0 : int(values_.size());
  }
  int columnCount(const QModelIndex &parent = {}) const override {
    return parent.isValid() ? 0 : 4;
  }
  QVariant data(const QModelIndex &index,
                int role = Qt::DisplayRole) const override {
    if (!index.isValid() || index.row() < 0 || index.row() >= rowCount() ||
        index.column() < 0 || index.column() >= 4)
      return {};
    const auto &order = values_[std::size_t(index.row())];
    if (role == Id)
      return order.id;
    if (role == Priority)
      return order.priority;
    if (role == Open)
      return order.status == Status::open;
    if (role != Qt::DisplayRole && role != Qt::EditRole)
      return {};
    switch (index.column()) {
    case 0:
      return order.id;
    case 1:
      return QString::fromStdString(order.title);
    case 2:
      return order.priority;
    case 3:
      return order.status == Status::open ? "open" : "done";
    }
    return {};
  }
  QVariant headerData(int section, Qt::Orientation orientation,
                      int role) const override {
    if (orientation == Qt::Horizontal && role == Qt::DisplayRole &&
        section >= 0 && section < 4)
      return QStringList{"ID", "Title", "Priority", "Status"}.at(section);
    return QAbstractTableModel::headerData(section, orientation, role);
  }
  Qt::ItemFlags flags(const QModelIndex &index) const override {
    if (!index.isValid())
      return Qt::NoItemFlags;
    auto result = QAbstractTableModel::flags(index);
    if (index.column() == 1)
      result |= Qt::ItemIsEditable;
    return result;
  }
  bool setData(const QModelIndex &index, const QVariant &value,
               int role) override {
    if (role != Qt::EditRole || !index.isValid() || index.column() != 1 ||
        index.row() < 0 || index.row() >= rowCount())
      return false;
    auto candidate = values_[std::size_t(index.row())];
    candidate.title = value.toString().toStdString();
    auto saved = service_.save(candidate);
    if (!succeeded(saved)) {
      lastError_ = QString::fromStdString(std::get<Error>(saved).message);
      return false;
    }
    values_[std::size_t(index.row())] = std::move(candidate);
    lastError_.clear();
    emit dataChanged(index, index, {Qt::DisplayRole, Qt::EditRole});
    return true;
  }
  Result<Done> refresh() {
    auto loaded = service_.list();
    if (!succeeded(loaded))
      return std::get<Error>(loaded);
    auto batch = std::get<std::vector<Order>>(std::move(loaded));
    beginResetModel();
    values_.swap(batch);
    endResetModel();
    return Done{};
  }
  QString lastError() const { return lastError_; }
};
class OpenFilter : public QSortFilterProxyModel {
  bool onlyOpen_{false};

protected:
  bool filterAcceptsRow(int row, const QModelIndex &parent) const override {
    return QSortFilterProxyModel::filterAcceptsRow(row, parent) &&
           (!onlyOpen_ || sourceModel()
                              ->index(row, 0, parent)
                              .data(OrderModel::Open)
                              .toBool());
  }

public:
  explicit OpenFilter(QObject *parent = nullptr)
      : QSortFilterProxyModel(parent) {
    setFilterKeyColumn(1);
    setFilterCaseSensitivity(Qt::CaseInsensitive);
  }
  void setOnlyOpen(bool value) {
    onlyOpen_ = value;
    invalidateFilter();
  }
};
} // namespace orders
Expected result

An incorrectly mapped proxy index would fail the data comparison.

05Check keyboard interaction

Add Ctrl+L to focus the title field. The solution uses a QShortcut owned by the editor. The test begins with focus in the search field, sends the shortcut and expects focus plus selected text in the title field. It also checks that moving focus does not save data.

solution.cpp · cppOpen file
#include "order_editor.hpp"
#include <QShortcut>
#include <QtTest>
void addTitleShortcut(orders::OrderEditor &editor) {
  auto *shortcut = new QShortcut(QKeySequence("Ctrl+L"), &editor);
  QObject::connect(shortcut, &QShortcut::activated, &editor, [&editor] {
    auto *title = editor.findChild<QLineEdit *>("title");
    title->setFocus();
    title->selectAll();
  });
}
class ShortcutTest : public QObject {
  Q_OBJECT
private slots:
  void focusAndSelection() {
    orders::MemoryRepository repository;
    orders::OrderService service(repository);
    orders::OrderEditor editor(service);
    addTitleShortcut(editor);
    editor.show();
    editor.activateWindow();
    QTRY_VERIFY_WITH_TIMEOUT(editor.isActiveWindow(), 2000);
    auto *title = editor.findChild<QLineEdit *>("title");
    title->setText("Existing draft");
    auto *search = editor.findChild<QLineEdit *>("search");
    search->setFocus();
    QTest::keyClick(search, Qt::Key_L, Qt::ControlModifier);
    QTRY_VERIFY_WITH_TIMEOUT(title->hasFocus(), 2000);
    QCOMPARE(title->selectedText(), QString("Existing draft"));
    QVERIFY(std::get<std::vector<orders::Order>>(service.list()).empty());
  }
};
QTEST_MAIN(ShortcutTest)
#include "solution.moc"
Expected result

Ctrl+L selects Existing draft in the title field.

06Understand automated UI test limits

python3 verify.py defaults to Qt offscreen for automated runs, allowing an event loop without a visible desktop. The keyboard test uses bounded QTRY waits for asynchronous conditions. This does not verify a native Windows session, screen-reader interaction or subjective visual quality.

verify.py · pythonOpen file
"""Build all targets and run the example and solution tests."""

import os
import subprocess
from pathlib import Path

root = Path(__file__).resolve().parent
environment = dict(os.environ)
environment.setdefault("QT_QPA_PLATFORM", "offscreen")
for command in [
    ["cmake", "-S", ".", "-B", "build", "-DCMAKE_BUILD_TYPE=Debug"],
    ["cmake", "--build", "build", "--parallel", "2"],
    ["ctest", "--test-dir", "build", "--output-on-failure"],
]:
    subprocess.run(command, cwd=root, env=environment, check=True, timeout=600)
Expected result

The widget workflow and keyboard exercise pass in the documented Linux environment.

Your exercise

Add Ctrl+L to focus and fully select the title field. Test switching from the search field and ensure no save occurs.

Show the solution and explanation

A QShortcut owned by the editor connects activated to setFocus and selectAll. The test processes Qt events with a bounded wait and then checks that the repository is still empty.

solution.cpp · cppOpen file
#include "order_editor.hpp"
#include <QShortcut>
#include <QtTest>
void addTitleShortcut(orders::OrderEditor &editor) {
  auto *shortcut = new QShortcut(QKeySequence("Ctrl+L"), &editor);
  QObject::connect(shortcut, &QShortcut::activated, &editor, [&editor] {
    auto *title = editor.findChild<QLineEdit *>("title");
    title->setFocus();
    title->selectAll();
  });
}
class ShortcutTest : public QObject {
  Q_OBJECT
private slots:
  void focusAndSelection() {
    orders::MemoryRepository repository;
    orders::OrderService service(repository);
    orders::OrderEditor editor(service);
    addTitleShortcut(editor);
    editor.show();
    editor.activateWindow();
    QTRY_VERIFY_WITH_TIMEOUT(editor.isActiveWindow(), 2000);
    auto *title = editor.findChild<QLineEdit *>("title");
    title->setText("Existing draft");
    auto *search = editor.findChild<QLineEdit *>("search");
    search->setFocus();
    QTest::keyClick(search, Qt::Key_L, Qt::ControlModifier);
    QTRY_VERIFY_WITH_TIMEOUT(title->hasFocus(), 2000);
    QCOMPARE(title->selectedText(), QString("Existing draft"));
    QVERIFY(std::get<std::vector<orders::Order>>(service.list()).empty());
  }
};
QTEST_MAIN(ShortcutTest)
#include "solution.moc"

Project context and sources

Independent teaching project using FactoryForge's logistics theme. The existing FactoryForge source revision provides architectural context. SQLite, networking and import features introduced here belong to the teaching project. Order Lab JSON is a separate format.