beginInsertRows Contracts, QSortFilterProxyModel & Custom StyledItemDelegates

Mutate live models via beginInsertRows/endInsertRows without losing operator selection, map filtered QSortFilterProxyModel clicks back to source rows, support QUndoStack edits, and paint cells via delegates.

35 minfree previewLinux 6.12→ module 5 lab
What you'll learn
  • Bracket structural vector mutations inside inclusive beginInsertRows/endInsertRows and beginRemoveRows/endRemoveRows pairs so QPersistentModelIndex selections stay valid.
  • Filter and sort models zero-copy via QSortFilterProxyModel (beginFilterChange/endFilterChange, UserRole) while translating view indices with mapToSource.
  • Record reversible operator edits on QUndoStack/QUndoView and custom-paint cell badges in QStyledItemDelegate::paint without setIndexWidget bloat.

Structural Notification Contracts vs the beginResetModel Anti-Pattern

When live telemetry appends to m_rows at 20 Hz, calling beginResetModel(); endResetModel(); tells every attached QTableView and QSortFilterProxyModel that the entire universe was destroyed: operator row selection vanishes, open context menus close, and scrollbars snap violently! Granular notifications—beginInsertRows, endInsertRows, beginRemoveRows, endRemoveRows, and dataChanged—update QPersistentModelIndex trackers incrementally so selection glides smoothly as rows enter and leave.

Two invariants in QAbstractItemModel are non-negotiable. First, beginInsertRows(parent, first, last) and beginRemoveRows(parent, first, last) MUST execute BEFORE m_rows changes size, and end*Rows() executes immediately AFTER. Second, [first, last] is an INCLUSIVE index range: appending 1 item onto a 5-element vector (indices 0..4) calls beginInsertRows(QModelIndex(), 5, 5), never (5, 6)!

For non-structural edits—such as toggling an acknowledged flag on row r—do not touch insert/remove signals at all; mutate the struct field and emit dataChanged(index(r, 0), index(r, 3), {Qt::DisplayRole, Qt::ForegroundRole}).

fig_m05_l03_a.svg — Preserving selection, scroll position, and 60 Hz frame…

Figure 5.3a. Preserving selection, scroll position, and 60 Hz frame budgets on live filtered tables.

mental model: Calling beginResetModel() every time one new alarm arrives is like ripping down an entire airport departures board and bolting up a fresh frame—beginInsertRows announces exact slot coordinates first so QTableView and QSortFilterProxyModel slide existing selection markers smoothly by +1.

Where it stops working: Mechanical split-flap boards tolerate an extra clack, whereas mutating m_rows BEFORE beginInsertRows() or passing half-open (N, N + 1) instead of inclusive (N, N) corrupts QSortFilterProxyModel's internal index vector and crashes the application.

definition (beginInsertRows Bracket & ): beginInsertRows(parent, first, last) / endInsertRows() form a strict two-phase structural transaction on QAbstractItemModel: first and last are inclusive indices in the post-insert coordinate space (appending 1 row at size() == N passes (QModelIndex(), N, N)). QSortFilterProxyModel maintains bidirectional row/column permutation maps (mapToSource / mapFromSource) over a source model with zero data duplication.

ast_m05_l03.svg — Call beginInsertRows(p,N,N) before push_back,…step 1/4
  1. Step 1. Call beginInsertRows with inclusive [first, last] bounds BEFORE mutating m_rows, then call endInsertRows.
  2. Step 2. Always translate view click or selection indices through proxy->mapToSource(proxyIndex) before reading m_rows.
  3. Step 3. Route operator parameter and table edits through QUndoStack so mis-clicks reverse deterministically.
  4. Step 4. Use one shared QStyledItemDelegate with painter->save()/restore() instead of calling setIndexWidget() per row.

Figure 5.3b. Call beginInsertRows(p,N,N) before push_back, mapToSource on clicks, and use delegates.

QSortFilterProxyModel Coordinate Mapping, QUndoStack, and Flyweight Delegates

QSortFilterProxyModel wraps a source model to filter rows (filterAcceptsRow) and sort columns without copying a single TelemetrySample struct. In Qt 6.8, mutating filter parameters calls beginFilterChange() before updating the member threshold and endFilterChange(QSortFilterProxyModel::Direction::Rows) after. Crucially, QTableView signals emit PROXY QModelIndex coordinates—always translate via const QModelIndex srcIdx = proxy->mapToSource(proxyIdx); before indexing your source model!

When operators acknowledge alarms or tune calibration cells inside a table, wrapping mutations in QUndoCommand subclasses pushed onto a QUndoStack (undoStack->push(cmd) executes cmd->redo() immediately!) gives one-line Ctrl+Z / Ctrl+Y safety and free visual audit history via QUndoView.

Finally, resist calling tableView->setIndexWidget(idx, new QPushButton(...)) on large tables: 5,000 embedded widgets re-introduce the exact heap and layout freeze we eliminated in Lesson 5.2! Subclass QStyledItemDelegate::paint(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &idx) once, bracket custom drawing in p->save() / p->restore(), and render 25 visible severity pills at zero widget cost.

fig_m05_l03_b.svg — Exact coordinate rules across QAbstractItemModel…

Figure 5.3b. Exact coordinate rules across QAbstractItemModel notifications, proxies, QUndoStack, and delegates.

Model / View OperationCorrect Qt 6.8 MechanismBroken Anti-PatternFailure Symptom of Anti-Pattern
Append 1 row at N = m_rows.size()beginInsertRows({}, N, N) -> push_back -> endInsertRows()push_back before beginInsertRows({}, N, N+1)Off-by-one proxy crash or corrupted row count
Update 1 field in row rMutate field + emit dataChanged(tl, br, {roles})beginResetModel() + endResetModel()Wipes user selection, focus, and scroll position
Handle click on filtered QTableViewproxy->mapToSource(proxyIdx).row()sourceModel->at(proxyIdx.row())Acknowledges or deletes the WRONG backing record!
Render custom severity pill per rowSingle QStyledItemDelegate::paint (save/restore)view->setIndexWidget() per rowThousands of child QWidget allocations stall scrolling
learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat -H 37 -H 74 proxy_delegate_undo.cpp File: proxy_delegate_undo.cpp    #include <QAbstractTableModel>    #include <QPainter>    #include <QSortFilterProxyModel>    #include <QStyledItemDelegate>    #include <QUndoCommand>    #include <QUndoStack>    #include <vector>        struct AlarmEntry {        int id;        int severity; // 0=Info, 1=Warn, 2=Critical        bool acked = false;    };        class LiveAlarmModel final : public QAbstractTableModel {        Q_OBJECT    public:        enum Roles : int { SeverityRole = Qt::UserRole + 1 };        explicit LiveAlarmModel(QObject *parent = nullptr) : QAbstractTableModel(parent) {}            int rowCount(const QModelIndex &p = {}) const override {            return p.isValid() ? 0 : static_cast<int>(m_rows.size());        }        int columnCount(const QModelIndex &p = {}) const override { return p.isValid() ? 0 : 2; }            QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override {            if (!idx.isValid() || idx.row() >= static_cast<int>(m_rows.size())) return {};            const auto &a = m_rows[static_cast<std::size_t>(idx.row())];            if (role == SeverityRole) return a.severity;            if (role != Qt::DisplayRole) return {};            return idx.column() == 0 ? QString::number(a.id)                                     : (a.acked ? tr("ACKED") : tr("ACTIVE"));        }            void appendAlarm(AlarmEntry entry) {            const int n = static_cast<int>(m_rows.size());          beginInsertRows(QModelIndex(), n, n); // Inclusive [n, n] BEFORE push_back!            m_rows.push_back(entry);            endInsertRows();        }            void setAcked(int sourceRow, bool acked) {            if (sourceRow < 0 || sourceRow >= static_cast<int>(m_rows.size())) return;            m_rows[static_cast<std::size_t>(sourceRow)].acked = acked;            const QModelIndex c = index(sourceRow, 1);            emit dataChanged(c, c, {Qt::DisplayRole});        }            bool isAcked(int sourceRow) const { return m_rows.at(static_cast<std::size_t>(sourceRow)).acked; }        private:        std::vector<AlarmEntry> m_rows;    };        class AckAlarmCommand final : public QUndoCommand {    public:        AckAlarmCommand(LiveAlarmModel *model, int srcRow, QUndoCommand *parent = nullptr)            : QUndoCommand(QObject::tr("Acknowledge Alarm"), parent),              m_model(model), m_row(srcRow), m_prev(model->isAcked(srcRow)) {}        void redo() override { m_model->setAcked(m_row, true); }        void undo() override { m_model->setAcked(m_row, m_prev); }        private:        LiveAlarmModel *m_model;        int m_row;        bool m_prev;    };        class SeverityProxy final : public QSortFilterProxyModel {        Q_OBJECT    public:        explicit SeverityProxy(QObject *parent = nullptr) : QSortFilterProxyModel(parent) {}        void setMinSeverity(int sev) {          if (m_min == sev) return;            beginFilterChange(); // Qt 6.8 directional filter update            m_min = sev;            endFilterChange(QSortFilterProxyModel::Direction::Rows);        }        protected:        bool filterAcceptsRow(int srcRow, const QModelIndex &srcParent) const override {            const QModelIndex idx = sourceModel()->index(srcRow, 0, srcParent);            return idx.data(LiveAlarmModel::SeverityRole).toInt() >= m_min;        }        private:        int m_min = 0;    };        class PillBadgeDelegate final : public QStyledItemDelegate {        Q_OBJECT    public:        using QStyledItemDelegate::QStyledItemDelegate;        void paint(QPainter *p, const QStyleOptionViewItem &opt, const QModelIndex &idx) const override {            if (idx.data(LiveAlarmModel::SeverityRole).toInt() < 2) {                QStyledItemDelegate::paint(p, opt, idx);                return;            }            p->save(); // Borrowed QPainter: always restore state!            p->setRenderHint(QPainter::Antialiasing, true);            const QRect r = opt.rect.adjusted(4, 3, -4, -3);            p->setPen(Qt::NoPen);            p->setBrush(QColor(0xB9, 0x1C, 0x1C));            p->drawRoundedRect(r, 4.0, 4.0);            p->setPen(QColor(0xF8, 0xFA, 0xFC));            p->drawText(r, Qt::AlignCenter, idx.data().toString());            p->restore();        }    };
  1. beginInsertRows((), n, n) runs BEFORE m_rows.push_back with inclusive [n, n] bounds.
  2. Qt 6.8 beginFilterChange() + endFilterChange(Direction::Rows) refreshes row filtering cleanly.
QSortFilterProxyModel-QUndoStack(3qt) at a glance — GL-Q01
QSortFilterProxyModel-QUndoStack(3qt) GL-Q01 Quick Reference QSortFilterProxyModel-QUndoStack(3qt) NAME       QSortFilterProxyModel, QStyledItemDelegate, QUndoStack - live proxy       mapping, delegates & undo SYNOPSIS       beginInsertRows(QModelIndex(), n, n); m_rows.push_back(x); endInsertRows();       const QModelIndex srcIdx = proxy->mapToSource(proxyIndex);       undoStack->push(new AckAlarmCommand(model, srcIdx.row()));       painter->save(); /* custom cell draw */ painter->restore(); CRITICAL RULES       1. [first, last] in beginInsertRows / beginRemoveRows is INCLUSIVE and       pre-mutation. 2. Never pass a proxy QModelIndex directly into       sourceModel methods without mapToSource(). 3. Use       QStyledItemDelegate::paint instead of setIndexWidget() on scrolling       tables. Kernel Systems Academy    Lesson 5.3     QSortFilterProxyModel-QUndoStack(3qt) GL-Q01 quick reference · full manual page: man 3qt QSortFilterProxyModel-QUndoStack 

Host C++20 Verifier for Persistent Selection, Proxy Mapping, and Undo/Redo

In verify.cpp, we verify all three dynamic Model/View contracts together: PersistentIndex row shifting across prepend insertions and deletions, FilterSortProxy map_to_source() translation, and UndoStack push / undo / redo acknowledgement state transitions.

Trace the sequence carefully: selecting row 1 (id = 102), prepending urgent id = 100 at row 0 shifts the persistent handle to row 2 (still id = 102), acknowledging via proxy.map_to_source(1) targets id = 102 accurately, and undo() / redo() toggles acked cleanly.

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat -H 20 -H 57 verify.cpp File: verify.cpp    #include <cassert>    #include <cstdio>    #include <memory>    #include <vector>        struct Alarm {        int id;        int sev;        bool acked = false;    };        class LiveStore {    public:        int track_persistent(int row) {            m_pers.push_back(row);            return static_cast<int>(m_pers.size() - 1U);        }        int persistent_row(int h) const noexcept { return m_pers[static_cast<std::size_t>(h)]; }          void insert_row(int pos, Alarm a) {            assert(pos >= 0 && pos <= static_cast<int>(m_rows.size()));            m_rows.insert(m_rows.begin() + pos, a);            for (int &r : m_pers) {                if (r >= pos) ++r;            }        }            void remove_row(int pos) {            assert(pos >= 0 && pos < static_cast<int>(m_rows.size()));            m_rows.erase(m_rows.begin() + pos);            for (int &r : m_pers) {                if (r == pos) r = -1;                else if (r > pos) --r;            }        }            void set_acked(int row, bool v) { m_rows.at(static_cast<std::size_t>(row)).acked = v; }        const Alarm &at(int row) const { return m_rows.at(static_cast<std::size_t>(row)); }        int count() const noexcept { return static_cast<int>(m_rows.size()); }        private:        std::vector<Alarm> m_rows;        std::vector<int> m_pers;    };        class ProxyMap {    public:        explicit ProxyMap(const LiveStore &src) noexcept : m_src(src) {}        void set_min_sev(int sev) {            m_min = sev;            rebuild();        }        void rebuild() {            m_map.clear();            for (int r = 0; r < m_src.count(); ++r) {                if (m_src.at(r).sev >= m_min) m_map.push_back(r);          }        }        int row_count() const noexcept { return static_cast<int>(m_map.size()); }        int map_to_source(int p_row) const noexcept {            return (p_row >= 0 && p_row < row_count()) ? m_map[static_cast<std::size_t>(p_row)] : -1;        }        private:        const LiveStore &m_src;        int m_min = 0;        std::vector<int> m_map;    };        class UndoAckStack {    public:        void push_ack(LiveStore &store, int src_row) {            const bool prev = store.at(src_row).acked;            store.set_acked(src_row, true);            m_cmds.resize(m_idx);            m_cmds.push_back({src_row, prev});            ++m_idx;        }        void undo(LiveStore &store) {            assert(m_idx > 0);            --m_idx;            store.set_acked(m_cmds[m_idx].row, m_cmds[m_idx].prev);        }        void redo(LiveStore &store) {            assert(m_idx < m_cmds.size());            store.set_acked(m_cmds[m_idx].row, true);            ++m_idx;        }        private:        struct Cmd {            int row;            bool prev;        };        std::vector<Cmd> m_cmds;        std::size_t m_idx = 0;    };        int main() {        LiveStore store;        store.insert_row(0, {101, 0, false});        store.insert_row(1, {102, 2, false});        store.insert_row(2, {103, 1, false});            const int h_sel = store.track_persistent(1); // id=102        store.insert_row(0, {100, 2, false});        // prepend -> sel shifts 1 -> 2        assert(store.persistent_row(h_sel) == 2 && store.at(2).id == 102);            ProxyMap proxy(store);        proxy.set_min_sev(2); // Keeps src rows 0 (id=100) and 2 (id=102)        assert(proxy.row_count() == 2);        const int clicked_src = proxy.map_to_source(1);        assert(clicked_src == 2 && store.at(clicked_src).id == 102);            UndoAckStack undo;        undo.push_ack(store, clicked_src);        assert(store.at(2).acked);        undo.undo(store);        assert(!store.at(2).acked);        undo.redo(store);        assert(store.at(2).acked);            store.remove_row(2); // Evict selected row -> handle becomes -1        assert(store.persistent_row(h_sel) == -1);            std::printf("proxy_undo_audit: crit_rows=%d mapped_src=%d redo_acked=1 evicted_handle=%d\n",                    proxy.row_count(), clicked_src, store.persistent_row(h_sel));        return 0;    }
  1. Inserting at pos shifts all persistent indices >= pos upward by +1 so operator selection stays locked on id=102.
  2. map_to_source(1) translates filtered proxy row 1 into backing source row 2 before UndoAckStack mutates store.

Verifying Persistent Shifts, Proxy Coordinate Mapping, and Undo History

Confirm ./verify outputs proxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1. Without map_to_source(1), indexing store.at(1) directly would have acknowledged id = 101 (Info) instead of id = 102 (Critical)!

Now put the complete bounded ring-buffer model, persistent selection shifter, and sort/filter proxy through lab_m05_table_model_roles.

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l03./verifyproxy_undo_audit: crit_rows=2 mapped_src=2 redo_acked=1 evicted_handle=-1learner@ksa:~/gl-q01/m05-l03
strace — learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03strace -e trace=write,exit_group ./verifywrite(1, "proxy_undo_audit: crit_rows=2 ma"..., 74) = 74exit_group(0)                           = ?+++ exited with 0 +++

Proxy Row Mix-Ups, Painter State Leaks, and Half-Open Insert Bounds

Granular beginInsertRows/beginRemoveRows brackets, zero-copy QSortFilterProxyModel views, QUndoStack commands, and flyweight QStyledItemDelegate rendering form the gold-standard Qt 6 data-grid architecture.

In Module 6, we complete GL-Q01 with crash-atomic QSaveFile configuration persistence, premultiplied ARGB32 QPainter gauges, ring-buffered QtCharts, and headless QTest TAP 13 suites.

Passing Proxy QModelIndex Rows Directly to the Source Model:

  • Symptom: Filtering a fault log to 'Critical Only' and clicking 'Clear Row' deletes an unrelated 'Info' record hidden at row 0 of the source vector.
  • Root Cause: View signals emit QModelIndex coordinates belonging to QSortFilterProxyModel, whose row 0 maps to an arbitrary source row.
  • Fix: Always call const QModelIndex srcIdx = proxy->mapToSource(proxyIdx); and check srcIdx.isValid() before touching source storage.

Mutating Shared QPainter Pens or Clips Inside QStyledItemDelegate::paint Without restore():

  • Symptom: Every column to the right of column 2 renders with a thick red pen, no border, or clipped text.
  • Root Cause: QAbstractItemView passes one shared QPainter* across consecutive cells during paintEvent; un-restored brush/pen changes bleed into subsequent cells.
  • Fix: Call painter->save() before modifying pens, brushes, render hints, or clips, and pair with painter->restore() on every return path.

Guided Practice

Extend ProxyMap in verify.cpp with map_from_source(int src_row) returning the proxy row index (or -1 if filtered out), and assert that map_from_source(1) (id = 101, sev = 0) returns -1 while map_from_source(2) (id = 102, sev = 2) returns 1.

Independent Practice

Complete lab_m05_table_model_roles by fixing the three defects in starter/core.cpp: returning empty RoleValue{} for DataRole::CheckState, decrementing surviving persistent row handles when FIFO capacity evicts row 0, and translating FaultFilterProxy::data through map_to_source(proxy_row).

Verification Checks

quiz · 1 of 3

m_rows currently holds 6 elements (indices 0..5). Which exact sequence validly appends 1 new record to a QAbstractTableModel?

quiz · 2 of 3

A QTableView is attached to SeverityProxy *proxy wrapping LiveAlarmModel *src. Inside connect(view, &QTableView::doubleClicked, ...), how do you locate the clicked AlarmEntry?

quiz · 3 of 3

Why is QStyledItemDelegate::paint vastly more scalable than QTableView::setIndexWidget() for rendering status pills in a 10,000-row table?

Lab 5: Bounded FaultTableModel, Persistent Selection & Sort/Filter Proxy

env: host

1. Motivation

Implement and verify a bounded-capacity FaultTableModel and FaultFilterProxy with multi-role data() dispatch, FIFO persistent-selection tracking, and map_to_source coordinate translation.

2. Learning objectives

  • Guard flat row_count/column_count against valid parents and return empty RoleValue{} on unhandled CheckState queries.
  • Maintain QPersistentModelIndex-equivalent selection handles across FIFO capacity eviction and in-place alarm acknowledgement.
  • Filter and sort alarms zero-copy via UserSeverity while translating proxy rows accurately with map_to_source.

3. Environment requirements

All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).

4. Required software and hardware

  • Host workstation: g++ (-std=c++20 -Wall -Wextra -Werror -pedantic), GNU make, ar (binutils), and POSIX /bin/sh.
  • Target environment (optional hardware step, Section 13): ARMv7-A Cortex-A7 operator console (512 MiB DDR3) running Linux kernel 6.12 LTS and Qt 6.8 QTableView + QSortFilterProxyModel over live SocketCAN fault telemetry.

5. Complete executable commands

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat script.sh File: script.sh    make -B -C files    ./files/lab_cli    ./files/lab_cli --bench    sh check.sh

6. Annotated source code

files/core.cpp enforces the production invariants that starter/core.cpp breaks:

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat example.cpp File: example.cpp    void FaultTableModel::append_fault(FaultItem item) {        if (m_rows.size() == m_capacity) {            m_rows.erase(m_rows.begin());            for (int &r : m_persistent) {                if (r == 0) r = -1;     // Evicted row becomes invalid                else if (r > 0) --r;    // Surviving selections shift -1            }        }        m_rows.push_back(std::move(item));    }        RoleValue FaultFilterProxy::data(int proxy_row, int col, DataRole role) const {        const int src_row = map_to_source(proxy_row); // Never index m_src with raw proxy_row!        return (src_row < 0) ? RoleValue{} : m_src.data(src_row, col, role);    }

starter/core.cpp contains three realistic Model/View bugs: FaultTableModel::data falls through on DataRole::CheckState (causing phantom checkboxes), append_fault forgets --r on surviving persistent selections during FIFO eviction, and FaultFilterProxy::data passes unmapped proxy_row straight to m_src.

7. Expected output

Passing files/ run (sh check.sh, exit code 0):

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic    ok 2 - archives core.o into libcore.a and links independent TAP verifier    ok 3 - enforces flat parent=0 guard, typed UserCode/Foreground roles, and empty unhandled CheckStateRole    ok 4 - evicts oldest FIFO row at capacity, shifts persistent selections, and updates ack state in place    ok 5 - filters and sorts FaultFilterProxy by UserSeverity and translates proxy data() via map_to_source    # pass 5/5

CLI verification output (./files/lab_cli):

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt    table_model: rows=1024 crit_proxy_rows=341 top_src=1021 top_code=E132

Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.

8. Explanation of observed behavior

Check 3 verifies row_count(true) == 0, !data(CheckState).valid, and UserCode/Foreground projections. Check 4 overflows a 3-row ring buffer, proving handle h0 invalidates to -1 while h1 (seq_id = 11) shifts cleanly from row 1 to row 0 and clears its crimson Foreground role upon set_acknowledged(0, true). Check 5 configures FaultFilterProxy (min_severity = 1, descending sort) and verifies map_to_source(0) == 4 (E505).

9. Experiment variations

  • Near transfer: Add a CommandUndoStack wrapper around FaultTableModel::set_acknowledged(row, acked) supporting acknowledge_all_critical() as one macro command whose undo() restores only previously unacknowledged rows.
  • Far transfer: Replace std::vector::erase(begin()) (O(capacity) memmove) with a power-of-two circular index (m_head + logical_row) & mask so 50,000-row ring eviction runs in O(1) array writes.

10. Performance measurements

Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):

learner@ksa: ~/gl-q01/m05-l03
learner@ksa:~/gl-q01/m05-l03$ bat listing.txt File: listing.txt    bench_proxy_refresh_ns: p50=36641 p95=46302 p99=49863 (sink=1136250)

The CLOCK_MONOTONIC benchmark measures host C++20 append_fault + 1,024-row FaultFilterProxy sort/filter rebuild latency (nanoseconds per cycle in host DRAM). On target Cortex-A7 hardware, incremental proxy maintenance via beginInsertRows avoids full std::stable_sort passes on every incoming frame.

11. Troubleshooting

SymptomRoot causeFix
Check 3 fails with phantom checkbox errorStarter code lets DataRole::CheckState fall into the DisplayRole switchRestore if (role != DataRole::Display) return {}; immediately before switch (col)
Check 4 fails with h1=1 instead of h1=0FIFO eviction erased row 0 without decrementing persistent handles r > 0Decrement --r for every persistent handle with r > 0 when row 0 is erased
Check 5 fails with text=E101 instead of E505FaultFilterProxy::data indexed m_src with proxy_row (0) instead of map_to_source(0) (4)Set const int src_row = map_to_source(proxy_row); before querying m_src

12. Guided questions

  1. Why does FaultFilterProxy sort using DataRole::UserSeverity integers rather than comparing DataRole::Display strings?
  • *Hint 1:* Consider both alphabetical order ('CRITICAL' vs 'INFO' vs 'WARN') and UI translations.
  • *Hint 2:* Alphabetical string sort orders 'CRITICAL' < 'INFO' < 'WARN' incorrectly and breaks completely under localization, whereas integer UserSeverity (2 > 1 > 0) is fast and locale-invariant.
  1. Why did FaultFilterProxy::refresh() choose std::stable_sort instead of std::sort?
  • *Hint 1:* Think about ties when multiple alarms share the same severity and timestamp.
  • *Hint 2:* std::stable_sort preserves relative arrival order among equal-key elements deterministically across refreshes, preventing tied rows from jittering visually on screen.

13. Independent challenges

Upgrade FaultTableModel from std::vector::erase(begin()) to a true O(1) ring buffer (m_head, m_count) and compare ./files/lab_cli --bench p50 / p99 latencies at capacity = 32,768.

14. Solutions and explanations

Strict DisplayRole gating, pre-eviction persistent-handle shifting, and map_to_source coordinate translation keep bounded live telemetry views fast, accurate, and selection-safe.

Run locally in your terminal and check off each verification milestone.

Not started

Key takeaways

  • beginInsertRows(parent, first, last) and beginRemoveRows(parent, first, last) take inclusive [first, last] indices BEFORE mutating the backing vector, updating QPersistentModelIndex selections without resetting scroll state.
  • A view bound to QSortFilterProxyModel emits proxy QModelIndex coordinates that must be translated via proxy->mapToSource(proxyIdx) before indexing the source QAbstractItemModel.
  • QUndoStack and QUndoCommand (undo() / redo(), inspectable via QUndoView) encapsulate reversible operator table and parameter edits cleanly.
  • One flyweight QStyledItemDelegate::paint instance (painter->save() / restore()) custom-renders visible severity badges with zero extra QWidget allocations, unlike QAbstractItemView::setIndexWidget().
Progress is saved on this device.
up next · module 5 labLab: Bounded FaultTableModel, Persistent Selection & Sort/Filter Proxy (70 min)
→ module 5 lab

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure