← C++

C++ · 19 / 24

Qt model/view with sorting, filtering and editing

Separate order data from presentation while preserving record identity during sorting and editing.

  • Large
  • Advanced
  • 90 min

Prerequisites: Your first Qt interface with signals and slots, Replaceable repositories and focused test doubles

In this tutorial
  1. Set up Qt Widgets and Qt Test
  2. Map data and model roles
  3. Map proxy indexes correctly
  4. Run a deliberately temporary demo
  5. Check model contracts and signals
  6. Add a priority filter
  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. Qt model contracts, edit validation, persisted change, signal counts, sorting, filtering and model reset. Linux widget tests run without a visible desktop. Native Windows interaction is not verified.

A table row is not a permanent order ID. Once a UI sorts or filters, visible and original row numbers differ. We build a QAbstractTableModel, place a proxy model in front and save edits through the application service. A model tester also checks the rules Qt expects custom models to follow.

Package contents and individual files

01Set up Qt Widgets and Qt Test

Install Qt 6.8 with Widgets and Test. If CMake cannot find Qt, set CMAKE_PREFIX_PATH to your Qt installation. python3 verify.py builds the UI and its tests. AUTOMOC processes the test classes' meta-objects. Run ./build/order_lab in your desktop session for the visible demo.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(cpp_19 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
enable_testing()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
  add_compile_options(-Wall -Wextra -Wpedantic -Werror)
endif()
find_package(Qt6 6.8 REQUIRED COMPONENTS Core Test Widgets)
set(CMAKE_AUTOMOC ON)
add_executable(order_lab main.cpp)
target_link_libraries(order_lab PRIVATE Qt6::Core Qt6::Test Qt6::Widgets)
add_executable(lesson_tests tests.cpp)
target_link_libraries(lesson_tests PRIVATE Qt6::Core Qt6::Test Qt6::Widgets)
add_test(NAME lesson_tests COMMAND lesson_tests)
set_tests_properties(lesson_tests PROPERTIES TIMEOUT 30)
add_executable(exercise_solution solution.cpp)
target_link_libraries(exercise_solution PRIVATE Qt6::Core Qt6::Test Qt6::Widgets)
add_test(NAME exercise_solution COMMAND exercise_solution)
set_tests_properties(exercise_solution PROPERTIES TIMEOUT 30)
Expected result

A table displays three synthetic orders.

02Map data and model roles

rowCount and columnCount return 0 for a valid parent because this table has no children. DisplayRole contains visible values. Custom roles expose ID, priority and open status independently of the clicked column. setData validates and saves through the service before emitting dataChanged.

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 invalid title is rejected without a change signal.

03Map proxy indexes correctly

OpenFilter combines text search with an open-only filter. The table sorts through this proxy. Selection and deletion map the visible index back through mapToSource and read its ID. The demo edits through a form. Direct model editing is additionally exercised by tests.

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

Even after descending sort, the first visible row identifies the correct order.

04Run a deliberately temporary demo

The demo wires MemoryRepository, OrderService and OrderEditor in lifetime order. Search for motors, toggle the open-only filter and edit a title through the form. Data lives only in memory. Persistent storage follows in tutorial 21 and the capstone.

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

Searching for motors shows exactly one order.

05Check model contracts and signals

QAbstractItemModelTester watches both source and proxy models. QSignalSpy counts dataChanged. Tests cover invalid input, successful persistence, sorting, filters and clearing the batch. A model tester complements domain tests rather than replacing them.

tests.cpp · cppOpen file
#include "order_model.hpp"
#include "test_support.hpp"
#include <QAbstractItemModelTester>
#include <QSignalSpy>
#include <QtTest>
using namespace orders;
class ModelTests : public QObject {
  Q_OBJECT
private slots:
  void editingAndSorting() {
    MemoryRepository repository;
    OrderService service(repository);
    QVERIFY(succeeded(service.replace(samples())));
    OrderModel model(service);
    QAbstractItemModelTester tester(
        &model, QAbstractItemModelTester::FailureReportingMode::QtTest);
    QVERIFY(succeeded(model.refresh()));
    QCOMPARE(model.rowCount(), 3);
    QCOMPARE(model.rowCount(model.index(0, 0)), 0);
    QVERIFY(!model.data(model.index(90, 0)).isValid());
    QSignalSpy changed(&model, &QAbstractItemModel::dataChanged);
    QVERIFY(!model.setData(model.index(0, 1), "  ", Qt::EditRole));
    QCOMPARE(changed.count(), 0);
    QVERIFY(model.setData(model.index(0, 1), "New title", Qt::EditRole));
    QCOMPARE(changed.count(), 1);
    QVERIFY(std::get<std::vector<Order>>(service.list())[0].title ==
            "New title");
    OpenFilter proxy;
    proxy.setSourceModel(&model);
    QAbstractItemModelTester proxyTester(
        &proxy, QAbstractItemModelTester::FailureReportingMode::QtTest);
    proxy.sort(0, Qt::DescendingOrder);
    QCOMPARE(proxy.index(0, 0).data(OrderModel::Id).toInt(), 3);
    proxy.setOnlyOpen(true);
    QCOMPARE(proxy.rowCount(), 2);
    QCOMPARE(proxy.mapToSource(proxy.index(0, 0)).data(OrderModel::Id).toInt(),
             2);
    proxy.setFilterFixedString("new");
    QCOMPARE(proxy.rowCount(), 1);
    QVERIFY(succeeded(service.replace({})));
    QVERIFY(succeeded(model.refresh()));
    QCOMPARE(proxy.rowCount(), 0);
  }
};
QTEST_MAIN(ModelTests)
#include "tests.moc"
Expected result

All model checks pass. A valid edit emits exactly one change signal.

06Add a priority filter

Extend the existing filter to require priority 2. Continue calling its previous filter condition to preserve text search and the open-only setting. The solution checks the result count, actual ID and a subsequently emptied batch.

solution.cpp · cppOpen file
#include "order_model.hpp"
#include "test_support.hpp"
#include <QCoreApplication>
class PriorityFilter final : public orders::OpenFilter {
protected:
  bool filterAcceptsRow(int row, const QModelIndex &parent) const override {
    return orders::OpenFilter::filterAcceptsRow(row, parent) &&
           sourceModel()
                   ->index(row, 0, parent)
                   .data(orders::OrderModel::Priority)
                   .toInt() == 2;
  }
};
int main(int argc, char **argv) {
  QCoreApplication application(argc, argv);
  orders::MemoryRepository repository;
  orders::OrderService service(repository);
  service.replace(samples());
  orders::OrderModel model(service);
  model.refresh();
  PriorityFilter filter;
  filter.setSourceModel(&model);
  filter.setOnlyOpen(true);
  require(filter.rowCount() == 1, "urgent open order");
  require(filter.index(0, 0).data(orders::OrderModel::Id).toInt() == 1,
          "correct identity");
  service.replace({});
  model.refresh();
  require(filter.rowCount() == 0, "empty model");
}
Expected result

Only order 1 remains visible in the sample.

Your exercise

Add PriorityFilter as an extension of OpenFilter. Show only urgent orders at priority 2 while retaining existing filters. Check the result's ID and empty data.

Show the solution and explanation

The solution combines OpenFilter::filterAcceptsRow with the source model's Priority role. It does not depend on the currently visible column. After a model reset the result must also be empty.

solution.cpp · cppOpen file
#include "order_model.hpp"
#include "test_support.hpp"
#include <QCoreApplication>
class PriorityFilter final : public orders::OpenFilter {
protected:
  bool filterAcceptsRow(int row, const QModelIndex &parent) const override {
    return orders::OpenFilter::filterAcceptsRow(row, parent) &&
           sourceModel()
                   ->index(row, 0, parent)
                   .data(orders::OrderModel::Priority)
                   .toInt() == 2;
  }
};
int main(int argc, char **argv) {
  QCoreApplication application(argc, argv);
  orders::MemoryRepository repository;
  orders::OrderService service(repository);
  service.replace(samples());
  orders::OrderModel model(service);
  model.refresh();
  PriorityFilter filter;
  filter.setSourceModel(&model);
  filter.setOnlyOpen(true);
  require(filter.rowCount() == 1, "urgent open order");
  require(filter.index(0, 0).data(orders::OrderModel::Id).toInt() == 1,
          "correct identity");
  service.replace({});
  model.refresh();
  require(filter.rowCount() == 0, "empty model");
}

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.