#include "Table.h" #include CustomModel::CustomModel(QObject *parent) : QAbstractTableModel(parent) { tableData = { {"Item 1-1", "Item 1-2", "Item 1-3"}, {"Item 2-1", "Item 2-2", "Item 2-3"}, {"Item 3-1", "Item 3-2", "Item 3-3"} }; } int CustomModel::rowCount(const QModelIndex &) const { return tableData.size(); } int CustomModel::columnCount(const QModelIndex &) const { return tableData.isEmpty() ? 0 : tableData[0].size(); } QVariant CustomModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole) { return tableData[index.row()][index.column()]; } return QVariant(); } bool CustomModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid() && role == Qt::EditRole) { tableData[index.row()][index.column()] = value.toString(); emit dataChanged(index, index); return true; } return false; } Qt::ItemFlags CustomModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::NoItemFlags; return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled; } CustomTableDelegate::CustomTableDelegate(QObject *parent) : QStyledItemDelegate(parent) {} void CustomTableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { painter->save(); if (index.row() % 2 == 0) { painter->fillRect(option.rect, QColor(220, 220, 220)); } else { painter->fillRect(option.rect, Qt::white); } painter->drawText(option.rect, Qt::AlignCenter, index.data().toString()); painter->restore(); } CustomTableView::CustomTableView(QWidget *parent) : QTableView(parent) { setAlternatingRowColors(true); setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection); horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); }