Model/View vs Item-Widgets: QAbstractTableModel, QListView, QTreeView & Roles
Eliminate the O(R * C) heap-allocation wall of QTableWidget, QListWidget, and QTreeWidget by projecting contiguous std::vector telemetry through QAbstractTableModel, QModelIndex, and Qt::ItemDataRole.
What you'll learn
- Quantify why
QTableWidget,QListWidget, andQTreeWidgetstall at 50,000 records whereasQTableView,QListView, andQTreeViewrender visible viewports inO(visible)work. - Implement
QAbstractTableModel::rowCount,columnCount,headerData, and role-guardeddata()(Qt::DisplayRole,ForegroundRole,UserRole) over a flat C++20std::vector. - Enforce flat-table
parent.isValid() -> 0bounds, unhandled-roleQVariant{}returns, andQListView::setUniformItemSizes(true)optimizations.
Why Item-Based Convenience Widgets Hit a Memory and Latency Wall
Qt ships three pairs of data widgets that look deceptively similar: convenience item-widgets (QListWidget, QTableWidget, QTreeWidget) and true Model/View views (QListView, QTableView, QTreeView). Item-widgets embed a hidden internal model populated by heap-allocated QListWidgetItem, QTableWidgetItem, or QTreeWidgetItem objects—convenient for a 12-row baud-rate picker, disastrous for telemetry!
Do the arithmetic for a 50,000-row x 4-column industrial fault log: QTableWidget executes 200,000 separate new QTableWidgetItem allocations, converts 200,000 integers and strings into QVariant wrappers upfront, consumes tens of megabytes of fragmented heap, and freezes the GUI thread for over 100 ms.
With QTableView + QAbstractTableModel (or QListView + QAbstractListModel), your C++ data stays once inside std::vector<TelemetryRecord> (24 bytes * 50,000 = 1.2 MiB contiguous RAM). The view queries rowCount() to scale its scrollbar and calls data(index, role) ONLY for the ~25 rows visible on screen!
Figure 5.2a. Memory layout and GUI-thread latency comparison at 50,000 rows x 4 columns.
mental model: QTableWidget on 50,000 fault rows is like printing and laminating 200,000 paper index cards before opening a 25-row inspection window; QAbstractTableModel keeps the binary ledger in one flat array and formats only the 25 rows currently visible behind the glass.
Where it stops working: Glass adds zero cost per glance, whereas QTableView calls data(index, role) several times per visible cell during every scroll repaint—so data() must stay fast, const, and free of blocking I/O.
definition ( & Qt::): QModelIndex is a 24-byte (64-bit ABI) value locator combining row, column, a quintptr internalId/internalPointer (used by QAbstractItemModel / QTreeView hierarchies), and const QAbstractItemModel *. Qt::ItemDataRole (DisplayRole = 0, DecorationRole = 1, ForegroundRole = 9, CheckStateRole = 10, UserRole = 0x0100) selects which representation of that cell data() projects.
- Step 1. Avoid 200,000 individual heap item allocations by backing views directly with a contiguous std::vector<Record>.
- Step 2. Return 0 in rowCount(parent) and columnCount(parent) whenever parent.isValid() is true on flat models.
- Step 3. Expose typed UserRole integers for logic/sorting and return empty QVariant{} on unhandled roles.
- Step 4. Set uniformItemSizes / fixed vertical row heights so views compute 50,000-row scrollbars in O(1) time.
Figure 5.2b. Store records in std::vector<T>, serve visible cells via data(), and return {} else.
QModelIndex Lifetimes, Qt::ItemDataRole Facets, and Tree vs Flat Contracts
QModelIndex is a tiny stack value (row(), column(), internalPointer(), model()), never a long-lived handle. As soon as a row is inserted or evicted ahead of row k, any saved QModelIndex for row k points to the wrong record or out-of-bounds memory—never store QModelIndex as a class member!
Inside data(const QModelIndex &idx, int role), Qt::ItemDataRole cleanly separates presentation from typed domain values. One TelemetryRecord answers Qt::DisplayRole with formatted units ("418 kPa"), Qt::ForegroundRole with alarm crimson (#DC2626), Qt::TextAlignmentRole with right alignment, and Qt::UserRole + 1 with the raw int 418 so filter proxies never scanf formatted UI strings! Always return QVariant{} for unhandled roles—returning a string when Qt queries Qt::CheckStateRole renders an accidental checkbox inside every single cell!
Finally, note how QTreeView generalizes tables and lists: every model method receives const QModelIndex &parent. In a hierarchical QAbstractItemModel (such as a CANopen object-dictionary tree), index(r, c, parent) and parent(child) walk node pointers via createIndex(r, c, nodePtr). In a flat QAbstractTableModel, cells have NO child rows, so rowCount(parent) and columnCount(parent) must return 0 whenever parent.isValid()!
Figure 5.2b. Mapping QListView, QTableView, and QTreeView onto QAbstractItemModel virtual contracts.
| Widget / View Class | Backing Storage | 50,000-Row Heap Cost | Mandatory Performance / Correctness Rule |
|---|---|---|---|
QTableWidget / QListWidget | O(R*C) heap *WidgetItems | 200,000 heap objects (>15 MiB) | Restrict strictly to small static tables (< 200 rows) |
QTableView + QAbstractTableModel | Flat std::vector<Struct> | 0 item objects (1.2 MiB vector) | Return 0 if parent.isValid(); lock verticalHeader default height |
QListView + QAbstractListModel | Flat std::vector<Struct> / ring | 0 item objects | Call setUniformItemSizes(true) for O(1) scrollbar layout |
QTreeView + QAbstractItemModel | Node arena / tree pointers | 0 QTreeWidgetItem wrappers | Implement exact index() / parent() inverse via createIndex() |
learner@ksa:~/gl-q01/m05-l02$ bat -H 30 -H 66 telemetry_table_model.hpp File: telemetry_table_model.hpp #pragma once #include <QAbstractTableModel> #include <QColor> #include <QHeaderView> #include <QListView> #include <QString> #include <QTableView> #include <QVariant> #include <cstdint> #include <vector> struct TelemetrySample { std::uint64_t timestampMs; std::uint16_t channelId; std::int32_t valueKpa; std::uint8_t severity; // 0=Normal, 1=Warn, 2=Critical }; class TelemetryTableModel final : public QAbstractTableModel { Q_OBJECT public: enum CustomRoles : int { RawValueRole = Qt::UserRole + 1, SeverityRole = Qt::UserRole + 2, }; explicit TelemetryTableModel(QObject *parent = nullptr) : QAbstractTableModel(parent) {} int rowCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : static_cast<int>(m_rows.size()); } int columnCount(const QModelIndex &parent = QModelIndex()) const override { return parent.isValid() ? 0 : 4; } QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override { if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return {}; switch (section) { case 0: return tr("Timestamp (ms)"); case 1: return tr("Channel"); case 2: return tr("Pressure"); case 3: return tr("Severity"); default: return {}; } } QVariant data(const QModelIndex &idx, int role = Qt::DisplayRole) const override { if (!idx.isValid() || idx.row() < 0 || idx.row() >= static_cast<int>(m_rows.size())) { return {}; } const auto &s = m_rows[static_cast<std::size_t>(idx.row())]; if (role == RawValueRole) return s.valueKpa; if (role == SeverityRole) return static_cast<int>(s.severity); if (role == Qt::ForegroundRole && s.severity >= 2) { return QColor(0xDC, 0x26, 0x26); } if (role == Qt::TextAlignmentRole && idx.column() != 3) { return int(Qt::AlignRight | Qt::AlignVCenter); } if (role != Qt::DisplayRole) { return {}; // Mandatory: keeps CheckStateRole / DecorationRole empty! } switch (idx.column()) { case 0: return QVariant::fromValue(s.timestampMs); case 1: return QStringLiteral("CH-%1").arg(s.channelId, 2, 10, QLatin1Char('0')); case 2: return QStringLiteral("%1 kPa").arg(s.valueKpa); case 3: return s.severity >= 2 ? tr("CRITICAL") : (s.severity == 1 ? tr("WARN") : tr("OK")); default: return {}; } } static void tuneHighRateViews(QTableView *table, QListView *list) { table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); table->verticalHeader()->setDefaultSectionSize(28); list->setUniformItemSizes(true); // O(1) scrollbar geometry at 50,000 rows! } private: std::vector<TelemetrySample> m_rows; };- Returning 0 when parent.isValid() tells views that flat table cells do not own nested tree children.
- Returning empty QVariant{} for non-DisplayRole queries prevents accidental checkboxes on CheckStateRole.
QAbstractTableModel-Roles(3qt) GL-Q01 Quick Reference QAbstractTableModel-Roles(3qt) NAME QAbstractTableModel, QModelIndex, Qt::ItemDataRole - virtualized Model/View contracts SYNOPSIS int rowCount(const QModelIndex &p) const override { return p.isValid() ? 0 : m_rows.size(); } QVariant data(const QModelIndex &i, int role = Qt::DisplayRole) const override; listView->setUniformItemSizes(true); tableView->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed); MANDATORY INVARIANTS 1. Return QVariant{} for every unhandled role (especially Qt::CheckStateRole = 10). 2. Never cache transient QModelIndex values across model mutations. 3. Expose typed domain integers via Qt::UserRole + k rather than parsing DisplayRole strings. Kernel Systems Academy Lesson 5.2 QAbstractTableModel-Roles(3qt) GL-Q01 quick reference · full manual page: man 3qt QAbstractTableModel-Roles Host C++20 Benchmark Contrasting 50,000-Row Virtual Models vs Item Allocation
In verify.cpp, we populate 50,000 contiguous SampleRow structs (16 bytes each = 800 KiB) and measure CLOCK_MONOTONIC latency of 100-cell (25 x 4) viewport queries in the middle of the dataset (rows 25,000..25,024), comparing against eager 200,000-cell HeapWidgetCell construction.
Simultaneously, assertions verify row_count(valid_parent = true) == 0, !data(CheckState).valid, and typed UserSeverity / UserValue integer extraction without string parsing.
learner@ksa:~/gl-q01/m05-l02$ bat -H 35 -H 48 verify.cpp File: verify.cpp #include <algorithm> #include <array> #include <cassert> #include <cstdint> #include <cstdio> #include <ctime> #include <memory> #include <string> #include <vector> enum class Role { Display, Foreground, CheckState, UserValue, UserSeverity }; struct Variant { bool valid = false; std::int64_t num = 0; std::string str; }; struct Index { int row = -1; int col = -1; constexpr bool is_valid() const noexcept { return row >= 0 && col >= 0; } }; struct SampleRow { std::uint64_t ts_ms; std::int32_t kpa; std::uint16_t ch; std::uint8_t sev; }; class VirtualTelemetryModel { public: explicit VirtualTelemetryModel(std::vector<SampleRow> rows) noexcept : m_rows(std::move(rows)) {} int row_count(Index parent = {}) const noexcept { return parent.is_valid() ? 0 : static_cast<int>(m_rows.size()); } int col_count(Index parent = {}) const noexcept { return parent.is_valid() ? 0 : 4; } Variant data(Index idx, Role role) const { if (!idx.is_valid() || idx.row >= row_count() || idx.col >= col_count()) { return {}; } const auto &r = m_rows[static_cast<std::size_t>(idx.row)]; if (role == Role::UserValue) return {true, r.kpa, {}}; if (role == Role::UserSeverity) return {true, r.sev, {}}; if (role == Role::Foreground && r.sev >= 2) return {true, 0xDC2626, {}}; if (role != Role::Display) return {}; // CheckState stays invalid! switch (idx.col) { case 0: return {true, static_cast<std::int64_t>(r.ts_ms), std::to_string(r.ts_ms)}; case 1: return {true, r.ch, "CH-" + std::to_string(r.ch)}; case 2: return {true, r.kpa, std::to_string(r.kpa) + " kPa"}; case 3: return {true, r.sev, r.sev >= 2 ? "CRITICAL" : "OK"}; default: return {}; } } private: std::vector<SampleRow> m_rows; }; struct HeapWidgetCell { std::string text; std::uint32_t fg = 0; }; static std::uint64_t mono_ns() noexcept { timespec ts{}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast<std::uint64_t>(ts.tv_sec) * 1000000000ULL + static_cast<std::uint64_t>(ts.tv_nsec); } int main() { constexpr std::size_t kRows = 50000; std::vector<SampleRow> backing(kRows); for (std::size_t i = 0; i < kRows; ++i) { backing[i] = {10000ULL + i, static_cast<std::int32_t>(150 + (i % 320)), static_cast<std::uint16_t>(i % 8), static_cast<std::uint8_t>(i % 3)}; } // Measure eager O(R*C) item-widget build on 5,000 rows (scaled 10x conservative bound) const std::uint64_t t_eager0 = mono_ns(); std::vector<std::unique_ptr<HeapWidgetCell>> eager_cells; eager_cells.reserve(5000U * 4U); for (std::size_t r = 0; r < 5000U; ++r) { for (int c = 0; c < 4; ++c) { eager_cells.push_back(std::make_unique<HeapWidgetCell>( HeapWidgetCell{std::to_string(backing[r].kpa), 0U})); } } const std::uint64_t eager_5k_ns = mono_ns() - t_eager0; VirtualTelemetryModel model(std::move(backing)); assert(model.row_count() == 50000 && model.row_count({0, 0}) == 0); assert(!model.data({0, 0}, Role::CheckState).valid); assert(model.data({2, 0}, Role::UserSeverity).num == 2); assert(model.data({2, 3}, Role::Display).str == "CRITICAL"); std::array<std::uint64_t, 31> vp_ns{}; std::size_t sink = 0; for (std::size_t pass = 0; pass < vp_ns.size(); ++pass) { const std::uint64_t t0 = mono_ns(); for (int r = 25000; r < 25025; ++r) { for (int c = 0; c < 4; ++c) { sink += model.data({r, c}, Role::Display).str.size(); } } vp_ns[pass] = mono_ns() - t0; } std::sort(vp_ns.begin(), vp_ns.end()); assert(sink > 0 && eager_cells.size() == 20000U); std::printf("model_audit: rows=%d item_allocs=0 vp25_p50_ns=%llu eager5k_alloc_ns=%llu\n", model.row_count(), static_cast<unsigned long long>(vp_ns[15]), static_cast<unsigned long long>(eager_5k_ns)); return 0; }- Flat table model returns 0 when parent.is_valid() is true, matching QAbstractTableModel's leaf contract.
- Non-Display queries fall through to empty Variant{}, preventing CheckStateRole phantom checkboxes.
Comparing O(visible) Viewport Latency Against Eager Item Allocation
Inspect the ./verify output: rows=50000 item_allocs=0 renders a 25-row (100-cell) viewport straight out of the middle of 50,000 records in single-digit microseconds (vp25_p50_ns), whereas allocating even one-tenth (5,000 x 4 = 20,000) of an item-widget grid costs orders of magnitude more heap time (eager5k_alloc_ns).
Next, Lesson 5.3 solves live mutation: appending new telemetry, evicting oldest ring entries, sorting and filtering via QSortFilterProxyModel, undoing edits via QUndoStack, and custom-painting badges without ever resetting the user's scroll bar.
learner@ksa:~/gl-q01/m05-l02g++ -std=c++20 -Wall -Wextra -Werror -pedantic verify.cpp -o verifylearner@ksa:~/gl-q01/m05-l02./verifymodel_audit: rows=50000 item_allocs=0 vp25_p50_ns=15989 eager5k_alloc_ns=5646864learner@ksa:~/gl-q01/m05-l02learner@ksa:~/gl-q01/m05-l02strace -e trace=write,exit_group ./verifywrite(1, "model_audit: rows=50000 item_all"..., 81) = 81exit_group(0) = ?+++ exited with 0 +++Classic Custom Model Bugs: Phantom Checkboxes and ResizeToContents Freezes
Separating contiguous C++ backing storage from transient QModelIndex role queries scales QTableView, QListView, and QTreeView to tens of thousands of industrial records on modest embedded CPUs.
Keep host-versus-target measurements scoped accurately: host CLOCK_MONOTONIC timings measure pure C++20 data() formatting in DRAM, whereas target scroll smoothness on Cortex-A7 also includes QFontEngine glyph cache blits inside QStyledItemDelegate.
Returning Text Without Checking if (role == Qt::DisplayRole) in data():
- Symptom: Every cell across all four columns of QTableView renders an unwanted empty checkbox to the left of its text and bolds randomly.
- Root Cause: QStyledItemDelegate queries Qt::CheckStateRole (10) and Qt::FontRole (6) on every cell; a non-null QString QVariant coerces to 0 (Qt::Unchecked).
- Fix: Explicitly handle only intended roles (DisplayRole, ForegroundRole, UserRole + k) and return QVariant{} for all other roles.
Enabling QHeaderView::ResizeToContents on a 50,000-Row QTableView:
- Symptom: Despite using QAbstractTableModel, opening the table freezes the HMI for 800 ms on startup and on every inserted row.
- Root Cause: ResizeToContents forces the view to call data(DisplayRole) and measure font pixel width across all 50,000 rows instead of the 25 visible rows!
- Fix: Use QHeaderView::Interactive or QHeaderView::Fixed/Stretch column modes and fixed vertical row heights on large models.
Guided Practice
Extend VirtualTelemetryModel in verify.cpp with a header_data(int section, Role role) method that returns column titles ONLY when role == Role::Display and returns an invalid Variant{} for Role::CheckState, asserting that all 4 horizontal headers report non-empty titles and empty check states.
Independent Practice
Implement a two-level hierarchical DeviceTreeModel in ISO C++20 (parent() and index() using integer node indices 0..N-1 stored in an arena std::vector<Node>) representing 3 I2C buses with 4 sensor child nodes each, proving row_count(root) == 3, row_count(bus_i) == 4, and row_count(sensor) == 0.
Verification Checks
Key takeaways
- Convenience widgets (
QTableWidget,QListWidget,QTreeWidget) allocateO(R * C)heap item objects and duplicateQVariantstrings, whereasQTableView,QListView, andQTreeViewquerydata()only for visible viewport cells. QModelIndexis a transient stack coordinate (row,column,internalPointer,model *) that must never be cached across model insertions, removals, or resets.QAbstractItemModel::data(index, role)projects multiple facets from one C++ struct (Qt::DisplayRoletext,Qt::ForegroundRolecolor,Qt::UserRole + kraw typed integers) and must return emptyQVariant{}for unhandled roles.- A flat
QAbstractTableModelorQAbstractListModelmust return0fromrowCount(parent)wheneverparent.isValid()istrue, whereasQTreeViewmodels encode parent-child pointers viacreateIndex(row, col, ptr).