TableModel::setData can now be called for column 0 with different roles to edit. (Doesn't rely on Qt::EditRole and RoleForColumn in all cases)

This commit is contained in:
2026-03-09 07:46:28 +01:00
parent a6648b7d1e
commit c1ee2135df
3 changed files with 28 additions and 9 deletions

View File

@ -28,11 +28,11 @@ static UserRoles DEFAULT_ROLE = NameRole;
static QList<UserRoles> USER_FACING_ROLES = {NameRole, DescriptionRole, InfoRole,
TypeRole, AmountRole, FactorRole};
static QHash<int, QByteArray> ROLE_NAMES = {
{NameRole, "name"}, {DescriptionRole, "description"},
{InfoRole, "info"}, {TypeRole, "type"},
{AmountRole, "amount"}, {FactorRole, "factor"},
{ToStringRole, "ToString"}, {IdRole, "id"},
{Qt::DisplayRole, "display"}};
{NameRole, "name"}, {DescriptionRole, "description"},
{InfoRole, "info"}, {TypeRole, "type"},
{AmountRole, "amount"}, {FactorRole, "factor"},
{ToStringRole, "ToString"}, {IdRole, "id"},
{Qt::DisplayRole, "display"}, {Qt::EditRole, "edit"}};
static QList<UserRoles> STRING_ROLES = {NameRole, DescriptionRole, InfoRole, IdRole};
static QList<UserRoles> INT_ROLES = {AmountRole};

View File

@ -104,10 +104,9 @@ QVariant TableModel::headerData(int section, Qt::Orientation orientation, int ro
}
bool TableModel::setData(const QModelIndex& index, const QVariant& value, int role) {
if (role == Qt::EditRole && checkIndex(index)) {
const int column = index.column();
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
return setItemData(index, {{roleForColumn, value}});
if (checkIndex(index)) {
const int adjustedRole = getAppropriateRoleForIndex(index, role);
return setItemData(index, {{adjustedRole, value}});
}
return false;
}
@ -329,6 +328,25 @@ bool TableModel::isEmptyValueEqualToZero(const int role) const {
}
}
int TableModel::getAppropriateRoleForIndex(const QModelIndex& index, const int role) const {
/// cases:
/// 1. Qt::DisplayRole, Qt::EditRole
/// -> get role for column
/// 2. other roles
/// -> use role as given
const int column = index.column();
const int roleForColumn = GET_ROLE_FOR_COLUMN(column);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return roleForColumn;
break;
default:
return role;
break;
}
}
QModelIndex TableModel::searchItemIndex(const ModelItemValues givenItemValues) const {
// iterate over indexes to search item : see searchItem(...);
// for (const shared_ptr<ModelItem>& item : m_items) {

View File

@ -71,6 +71,7 @@ class TableModel : public QAbstractTableModel {
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const;
bool isEmptyValueEqualToZero(const int role) const;
int getAppropriateRoleForIndex(const QModelIndex& index, const int role) const;
QModelIndex searchItemIndex(const ModelItemValues givenItemValues) const;
bool isItemEqualToItemValues(const QModelIndex& itemIndex,
const ModelItemValues givenItemValues) const;