Skip to main content

Data Table

A model based table recipe with a sortable and filterable Qt proxy model.

Loading preview…
#include <QApplication>
#include <QFile>
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
#include <QStandardItemModel>
#include <QUrl>
#include <QVBoxLayout>
#include <array>
#ifdef SHADCN_GALLERY_MEDIA
#include <shadcn/media.hpp>
#endif
#include <shadcn/shadcn.hpp>

QWidget* example(QWidget* parent = nullptr) {
using namespace shadcn;
const QString name = "data-table";
auto* canvas = new QWidget(parent);
canvas->setAutoFillBackground(true);
auto* outer = new QHBoxLayout(canvas);
outer->setContentsMargins(32, 32, 32, 32);
auto* host = new QWidget(canvas);
auto* layout = new QVBoxLayout(host);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(16);
outer->addStretch();
outer->addWidget(host, 0, Qt::AlignCenter);
outer->addStretch();
Table* table =
name == "data-table" ? static_cast<Table*>(new DataTable(host)) : new Table(host);
table->setFixedSize(440, 185);
auto* model = new QStandardItemModel(table);
model->setHorizontalHeaderLabels({"Invoice", "Status", "Amount"});
model->appendRow(
{new QStandardItem("INV001"), new QStandardItem("Paid"), new QStandardItem("$250.00")});
model->appendRow({new QStandardItem("INV002"), new QStandardItem("Pending"),
new QStandardItem("$150.00")});
model->appendRow(
{new QStandardItem("INV003"), new QStandardItem("Paid"), new QStandardItem("$350.00")});
if (auto* data = qobject_cast<DataTable*>(table)) {
data->setSourceModel(model);
auto* filter = new Input(host);
filter->setPlaceholderText("Filter invoices...");
QObject::connect(filter, &Input::textChanged, data,
[data](const QString& text) { data->setFilter(text); });
layout->addWidget(filter);
} else
table->setModel(model);
layout->addWidget(table);
return canvas;
}

Installation​

add_subdirectory(shadcn-cpp)
target_link_libraries(app PRIVATE shadcn::widgets)

Usage​

#include <shadcn/data.hpp>
#include <QStandardItemModel>

QStandardItemModel model(0, 2, parent);
shadcn::DataTable table(parent);
table.setSourceModel(&model);
table.setFilter("ready");

DataTable keeps the source model separate from its proxy. Add rows to the source model and use setFilter for a text filter across all columns or one column.

Keyboard and accessibility​

Set clear header labels and a useful selection mode on the inherited QTableView. Keep filter controls labelled outside the table.

Ownership​

The data table owns its proxy model. The source model passed to setSourceModel remains owned by the caller and must outlive the table.

Known limits​

Sorting, editing delegates and server side pagination remain application responsibilities.