Skip to main content

Table

A themed QTableView for model based rows and columns.

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 = "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(2, 2, parent);
model.setHeaderData(0, Qt::Horizontal, "Name");
model.setHeaderData(1, Qt::Horizontal, "State");

shadcn::Table table(parent);
table.setModel(&model);

API​

Table inherits QTableView; use Qt models, selection modes, headers and delegates for table behavior.

Variations​

Use DataTable when filtering through a proxy model is needed.

Keyboard and accessibility​

Qt supplies native focus, keyboard interaction and accessible object roles. Give the component a visible label or an accessible name when its text alone does not explain the action.

Ownership​

The parent widget owns the component. Child widgets created through a component layout follow Qt parent ownership. References returned by helper methods are borrowed.