From 54d537dc9b1c325a56119404a5b21cff108d75b7 Mon Sep 17 00:00:00 2001 From: Bent Witthold Date: Thu, 2 Apr 2026 09:37:36 +0200 Subject: [PATCH] Roles can now be declared read-only. First read-only role: IdRole --- model/metadata.h | 12 +++++++++--- model/tablemodel.cpp | 15 +++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/model/metadata.h b/model/metadata.h index 8684e94..3597df8 100644 --- a/model/metadata.h +++ b/model/metadata.h @@ -25,9 +25,12 @@ enum UserRoles { static UserRoles DEFAULT_ROLE = NameRole; // TODO ?rename USER_FACING_ROLES -> MAIN_ROLES ? -static QList USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, - TypeRole, AmountRole, FactorRole}; -static QHash ROLE_NAMES = { +static QList USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole, TypeRole, + AmountRole, FactorRole, IdRole}; + +static QList READ_ONLY_ROLES = {IdRole}; + +static QHash ROLE_NAMES = { {NameRole, "name"}, {DescriptionRole, "description"}, {InfoRole, "info"}, {TypeRole, "type"}, {AmountRole, "amount"}, {FactorRole, "factor"}, @@ -71,6 +74,9 @@ static UserRoles GET_ROLE_FOR_COLUMN(const int column) { case 5: return FactorRole; break; + case 6: + return IdRole; + break; default: qWarning() << QString("No role found for column %1! Returning 'NameRole'...").arg(column); return NameRole; diff --git a/model/tablemodel.cpp b/model/tablemodel.cpp index 860bae0..7c14d21 100644 --- a/model/tablemodel.cpp +++ b/model/tablemodel.cpp @@ -40,10 +40,19 @@ TableModel::TableModel(QUndoStack* undoStack, QObject* parent) , m_undoStack(undoStack) {} Qt::ItemFlags TableModel::flags(const QModelIndex& index) const { + Qt::ItemFlags result = QAbstractTableModel::flags(index); if (!index.isValid()) { - return QAbstractTableModel::flags(index); + return result; } - return Qt::ItemIsEditable | QAbstractTableModel::flags(index); + + const int column = index.column(); + const int roleForColumn = GET_ROLE_FOR_COLUMN(column); + /// roles which aren't editable by the user + if (READ_ONLY_ROLES.contains(roleForColumn)) { + return result; + } + + return result | Qt::ItemIsEditable; } QHash TableModel::roleNames() const { return ROLE_NAMES; } @@ -341,8 +350,6 @@ int TableModel::getAppropriateRoleForIndex(const QModelIndex& index, const int r } QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const { - // iterate over indexes to search item : see searchItem(...); - // for (const shared_ptr& item : m_items) { for (int row = 0; row < rowCount(); ++row) { qDebug() << "Processing item at row" << row << "..."; QModelIndex itemIndex = index(row, 0);