Compare commits

..

27 Commits

Author SHA1 Message Date
c09aad88dc Merge branch 'feature/UndoRedoWithModelData' into develop 2025-12-22 11:38:13 +01:00
e54204e394 Editing an item is now undo/redo-able. 2025-12-15 18:04:14 +01:00
772ab6b2ff Reordered function implementations according to declarations in header file. 2025-12-12 13:22:27 +01:00
c75d35179b Deleting items from the model can now be made undone/redone. 2025-12-11 15:49:16 +01:00
0166a00d9d Adding new items to the model can now be made undone/redone. 2025-12-11 15:47:55 +01:00
432e81d4be Merge branch 'develop' into feature/UndoRedoWithModelData 2025-12-09 09:57:22 +01:00
e21c899aac Bugfix: Last row could not be removed due to miscalculations of the bounds. 2025-12-09 09:33:46 +01:00
169d8f9f1e Items can be deleted from the model. 2025-12-08 14:50:13 +01:00
d45b1098f9 Added default invalid parentIndex to TableModel::columnCount and added Q_UNUSED macro to suppress warnings. 2025-12-08 13:33:05 +01:00
4c906099eb Items can be added to model dynamically. 2025-12-08 13:25:02 +01:00
144460b5aa Start with the current data, when editing a table cell. 2025-12-06 14:34:17 +01:00
5b5713c89f Added a QUndoStack and made it accessible for UIs. 2025-12-06 10:34:44 +01:00
a07e03d80d Deducing the column count of the table model from the header names. 2025-12-04 15:54:53 +01:00
40e1dd3002 A very simple version of editing model data. 2025-12-04 11:30:30 +01:00
16c524f7a2 Proper header names for the columns. 2025-12-04 11:29:33 +01:00
0dba9639e6 Added a ModelItem class to hold the data for each row. 2025-12-03 11:07:39 +01:00
6a3725bde7 Added a simple read-only TableModel and made it accessible via GenericCore.
Basically like in this tutorial: https://doc.qt.io/qt-6/modelview.html#2-1-a-read-only-table
2025-12-02 16:09:34 +01:00
301d143b37 Updated core library project version to 0.1.0 2025-11-04 21:23:26 +01:00
13b53683a5 Retrieving Application name from umbrella project and using it to determine the path of the QtMaintenanceTool. 2025-11-01 10:52:04 +01:00
7ba0304232 Added SettingsHandler class. 2025-10-31 15:24:06 +01:00
d943f2d89a Added checking for update and triggering the updater. 2025-10-31 14:47:27 +01:00
bddb6df3ee Formatting CMakeLists.txt 2025-10-26 13:03:43 +01:00
7ec346b5a5 Retrieving core name and version from CMakeLists.txt and use it in GenericCore::toString(). 2025-10-03 11:15:06 +02:00
b631f4200e Added toString() method. 2025-10-02 16:22:47 +02:00
0bbac662f4 Using qDebug() instead of iostream::cout(). And formatted files with clangformat. 2025-10-02 16:22:01 +02:00
b3718c211f Using TARGET_APP variable in CMakeLists.txt. 2025-10-02 16:19:32 +02:00
fd32b85554 Added some console outputs to use library. 2025-10-02 13:42:13 +02:00
19 changed files with 920 additions and 15 deletions

View File

@ -1,6 +1,7 @@
cmake_minimum_required(VERSION 3.16) cmake_minimum_required(VERSION 3.16)
project(GenericCore LANGUAGES CXX) set(TARGET_APP "GenericCore")
project(${TARGET_APP} VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON) set(CMAKE_AUTOMOC ON)
@ -8,20 +9,32 @@ set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core LinguistTools) find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core LinguistTools)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core LinguistTools Gui)
set(TS_FILES GenericCore_en_US.ts) configure_file(CoreConfig.h.in CoreConfig.h)
add_library(GenericCore STATIC set(TS_FILES ${TARGET_APP}_en_US.ts)
add_library(${TARGET_APP} STATIC
genericcore.cpp genericcore.cpp
genericcore.h genericcore.h
${TS_FILES} ${TS_FILES}
constants.h
data/settingshandler.h data/settingshandler.cpp
model/tablemodel.h model/tablemodel.cpp
model/modelitem.h model/modelitem.cpp
formats/jsonparser.h formats/jsonparser.cpp
model/commands/insertrowscommand.h model/commands/insertrowscommand.cpp
model/commands/removerowscommand.h model/commands/removerowscommand.cpp
model/commands/edititemcommand.h model/commands/edititemcommand.cpp
) )
target_link_libraries(GenericCore PRIVATE Qt${QT_VERSION_MAJOR}::Core) include_directories(${CMAKE_CURRENT_BINARY_DIR})
target_compile_definitions(GenericCore PRIVATE GENERICCORE_LIBRARY) target_link_libraries(${TARGET_APP} PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Gui)
target_compile_definitions(${TARGET_APP} PRIVATE ${TARGET_APP}_LIBRARY)
if(COMMAND qt_create_translation) if(COMMAND qt_create_translation)
qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES})

2
CoreConfig.h.in Normal file
View File

@ -0,0 +1,2 @@
#define CORE_NAME "${PROJECT_NAME}"
#define CORE_VERSION "${PROJECT_VERSION}"

15
constants.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include <QString>
/// Platform dependent
#ifdef Q_OS_LINUX
static const QString UPDATER_EXE = "maintenancetool";
#elif defined(Q_OS_MAC)
static const QString UPDATER_EXE = "maintenancetool.app/Contents/MacOS/maintenancetool";
#elif defined(Q_OS_WIN)
static const QString UPDATER_EXE = "maintenancetool.exe";
#endif
#endif // CONSTANTS_H

43
data/settingshandler.cpp Normal file
View File

@ -0,0 +1,43 @@
#include "settingshandler.h"
#include <QSettings>
QVariantMap SettingsHandler::getSettings(QString group) {
QSettings settings;
QVariantMap result;
if (!group.isEmpty()) {
settings.beginGroup(group);
}
foreach (QString key, settings.allKeys()) {
result.insert(key, settings.value(key));
}
if (!group.isEmpty()) {
settings.endGroup();
}
return result;
}
void SettingsHandler::saveSettings(QVariantMap settingMap, QString group) {
qInfo() << "saving settings...";
QSettings settings;
if (!group.isEmpty()) {
settings.beginGroup(group);
}
foreach (QString key, settingMap.keys()) {
// qDebug() << "saving:" << key << "-" << settingMap.value(key);
settings.setValue(key, settingMap.value(key));
}
if (!group.isEmpty()) {
settings.endGroup();
}
settings.sync();
}
SettingsHandler::SettingsHandler() {}

15
data/settingshandler.h Normal file
View File

@ -0,0 +1,15 @@
#ifndef SETTINGSHANDLER_H
#define SETTINGSHANDLER_H
#include <QVariantMap>
class SettingsHandler {
public:
static QVariantMap getSettings(QString group = "");
static void saveSettings(QVariantMap settingMap, QString group = "");
private:
SettingsHandler();
};
#endif // SETTINGSHANDLER_H

58
formats/jsonparser.cpp Normal file
View File

@ -0,0 +1,58 @@
#include "jsonparser.h"
#include <QJsonArray>
#include <QJsonObject>
#include "../model/tablemodel.h"
QList<QHash<int, QVariant>> JsonParser::toItemValuesList(const QByteArray& jsonData,
const QString& objectName) {
QList<QHash<int, QVariant>> result;
if (jsonData.isEmpty()) {
return result;
}
QJsonArray itemArray = extractItemArray(jsonData, objectName);
foreach (QJsonValue value, itemArray) {
QJsonObject itemJsonObject = value.toObject();
QHash<int, QVariant> values = jsonObjectToItemValues(itemJsonObject);
result.append(values);
}
return result;
}
QHash<int, QVariant> JsonParser::jsonObjectToItemValues(const QJsonObject& itemJsonObject) {
QHash<int, QVariant> values;
// TODO make this more generic (by reading from model meta data)
values[TableModel::NameRole] =
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::NameRole)].toString();
values[TableModel::DescriptionRole] =
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::DescriptionRole)].toString();
values[TableModel::InfoRole] =
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::InfoRole)].toString();
values[TableModel::AmountRole] =
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::AmountRole)].toInt();
values[TableModel::FactorRole] =
itemJsonObject[TableModel::ROLE_NAMES.value(TableModel::FactorRole)].toDouble();
return values;
}
JsonParser::JsonParser() {}
QJsonArray JsonParser::extractItemArray(const QByteArray& jsonData, const QString& objectName) {
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
QJsonArray itemArray;
if (objectName.isEmpty()) {
itemArray = doc.array();
} else {
QJsonObject rootObject = doc.object();
itemArray = rootObject.value(QString("items")).toArray();
}
return itemArray;
}

23
formats/jsonparser.h Normal file
View File

@ -0,0 +1,23 @@
#ifndef JSONPARSER_H
#define JSONPARSER_H
#include <QVariant>
class QJsonObject;
class QString;
class QByteArray;
class QJsonArray;
class JsonParser {
public:
static QList<QHash<int, QVariant>> toItemValuesList(const QByteArray& jsonData,
const QString& objectName = "");
private:
explicit JsonParser();
static QJsonArray extractItemArray(const QByteArray& jsonData, const QString& objectName);
static QHash<int, QVariant> jsonObjectToItemValues(const QJsonObject& itemJsonObject);
};
#endif // JSONPARSER_H

View File

@ -1,3 +1,100 @@
#include "genericcore.h" #include "genericcore.h"
GenericCore::GenericCore() {} #include <QCoreApplication>
#include <QDateTime>
#include <QDebug>
#include <QProcess>
#include <QSettings>
#include <QString>
#include "../../ApplicationConfig.h"
#include "CoreConfig.h"
#include "constants.h"
#include "model/tablemodel.h"
#include <QtGui/QUndoStack>
using namespace std;
GenericCore::GenericCore() {
qDebug() << "Creating core...";
// TODO let the model own its undo stack (& use TableModel::getUndoStack() if necessary)
m_modelUndoStack = new QUndoStack(this);
setupModels();
}
GenericCore::~GenericCore() { qDebug() << "Destroying core..."; }
QString GenericCore::toString() const {
return QString("%1 (Version %2)").arg(CORE_NAME).arg(CORE_VERSION);
}
void GenericCore::sayHello() const { qDebug() << "Hello from the core!"; }
bool GenericCore::isApplicationUpdateAvailable() {
QProcess process;
const QString programmString = getMaintenanceToolFilePath();
const QStringList checkArgs("--checkupdates");
process.start(programmString, checkArgs);
process.waitForFinished();
const int exitCode = process.exitCode();
if (process.error() != QProcess::UnknownError) {
qDebug() << "Error checking for updates";
emit displayStatusMessage("Error checking for updates");
return false;
}
QByteArray data = process.readAllStandardOutput();
QSettings settings;
settings.beginGroup("Application");
settings.setValue("lastCheckForUpdate", QDateTime::currentDateTimeUtc());
settings.endGroup();
settings.sync();
if (data.isEmpty() || data.contains("currently no updates")) {
qInfo() << "No updates available";
emit displayStatusMessage("No updates available.");
return false;
}
return true;
}
void GenericCore::triggerApplicationUpdate() {
// TODO include cleaness of undo stack
// if (!m_undoStack->isClean()) {
// saveItems();
// }
// QStringList args("update componentA componentB");
QStringList args("--start-updater");
QString toolFilePath = getMaintenanceToolFilePath();
QProcess::startDetached(toolFilePath, args);
}
QUndoStack* GenericCore::getModelUndoStack() const { return m_modelUndoStack; }
std::shared_ptr<TableModel> GenericCore::getModel() const { return m_mainModel; }
void GenericCore::setupModels() {
m_mainModel = make_shared<TableModel>(m_modelUndoStack, this);
// TODO add QAbstractItemModelTester
}
QString GenericCore::getMaintenanceToolFilePath() const {
QString applicationDirPath = QCoreApplication::applicationDirPath();
/// setting the applicationDirPath hard coded to test update feature from IDE
#ifdef QT_DEBUG
applicationDirPath = QString("/opt/%1").arg(APPLICATION_NAME);
#endif
#ifdef Q_OS_MAC
applicationDirPath.append("/../../..");
#endif
const QString filePath = applicationDirPath + "/" + UPDATER_EXE;
return filePath;
}

View File

@ -1,10 +1,40 @@
#ifndef GENERICCORE_H #ifndef GENERICCORE_H
#define GENERICCORE_H #define GENERICCORE_H
class GenericCore #include <QObject>
{
public: class QUndoStack;
class QAbstractItemModel;
class QString;
class TableModel;
class GenericCore : public QObject {
Q_OBJECT
public:
GenericCore(); GenericCore();
~GenericCore();
QString toString() const;
void sayHello() const;
bool isApplicationUpdateAvailable();
void triggerApplicationUpdate();
QUndoStack* getModelUndoStack() const;
std::shared_ptr<TableModel> getModel() const;
signals:
void displayStatusMessage(QString message);
private:
QUndoStack* m_modelUndoStack;
std::shared_ptr<TableModel> m_mainModel;
void setupModels();
QString getMaintenanceToolFilePath() const;
}; };
#endif // GENERICCORE_H #endif // GENERICCORE_H

View File

@ -0,0 +1,79 @@
#include "edititemcommand.h"
#include <QDebug>
#include "../tablemodel.h"
EditItemCommand::EditItemCommand(TableModel* model,
const QModelIndex& index,
QMap<int, QVariant>& changedValues,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_model(model)
, m_row(index.row()) {
qInfo() << "New EditCommand...";
QString commandText;
if (changedValues.size() == 1) {
qDebug() << "Only one value to change. Using more specific command text...";
const int role = changedValues.firstKey();
const QVariant value = changedValues.first();
QString roleName = model->roleNames().value(role);
switch (role) {
case TableModel::NameRole:
case TableModel::DescriptionRole:
case TableModel::InfoRole:
case TableModel::AmountRole:
case TableModel::FactorRole:
commandText = QString("Setting '%1' of item '%2' to '%3'")
.arg(roleName)
.arg(index.data(TableModel::NameRole).toString())
.arg(value.toString());
break;
default:
commandText = QString("Edit item '%1'").arg(index.data(TableModel::NameRole).toString());
break;
}
} else {
qDebug() << "More than one value to change. Using a generic command text...";
commandText = QString("Edit item '%1'").arg(index.data(TableModel::NameRole).toString());
}
setText(commandText);
m_newValues = changedValues;
/// storing old values for undo step
m_oldValues = getOldValues(index, changedValues);
}
void EditItemCommand::undo() {
qDebug() << "Undoing the EditCommand...";
m_model->execEditItemData(m_row, m_oldValues);
}
void EditItemCommand::redo() {
qDebug() << "(Re-)doing the EditCommand...";
m_model->execEditItemData(m_row, m_newValues);
}
const QMap<int, QVariant> EditItemCommand::getOldValues(
const QModelIndex& index,
const QMap<int, QVariant>& changedValues) const {
QMap<int, QVariant> result;
QMap<int, QVariant>::const_iterator i;
for (i = changedValues.constBegin(); i != changedValues.constEnd(); ++i) {
const int role = i.key();
const QVariant newValue = i.value();
const QVariant oldValue = index.data(role);
// TODO check if role is a editable role?
if (oldValue != newValue) {
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
result.insert(role, oldValue);
} else {
qInfo() << "oldValue is already the same as newValue:" << oldValue;
}
}
// QVariant oldModifiedDate = index.data(ModifiedDateUTCRole);
// result.insert(ModifiedDateUTCRole, oldModifiedDate);
return result;
}

View File

@ -0,0 +1,30 @@
#ifndef EDITITEMCOMMAND_H
#define EDITITEMCOMMAND_H
#include <QMap>
#include <QUndoCommand>
class TableModel;
class EditItemCommand : public QUndoCommand {
public:
EditItemCommand(TableModel* model,
const QModelIndex& index,
QMap<int, QVariant>& changedValues,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo();
void redo();
private:
TableModel* m_model = nullptr;
const int m_row;
QMap<int, QVariant> m_oldValues;
QMap<int, QVariant> m_newValues;
/// private functions
const QMap<int, QVariant> getOldValues(const QModelIndex& index,
const QMap<int, QVariant>& changedValues) const;
};
#endif // EDITITEMCOMMAND_H

View File

@ -0,0 +1,33 @@
#include "insertrowscommand.h"
#include <QDebug>
#include "../tablemodel.h"
InsertRowsCommand::InsertRowsCommand(TableModel* model,
int startRow,
QList<QHash<int, QVariant> > valueList,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_tableModel(model)
, m_startRow(startRow)
, m_valueList(valueList) {
qInfo() << "New InsertCommand...";
const QString commandText =
QString("inserting %1 item(s) on row %2").arg(valueList.length()).arg(startRow);
setText(commandText);
}
void InsertRowsCommand::undo() {
qDebug() << "Undoing the InsertCommand...";
if (m_tableModel) {
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
}
}
void InsertRowsCommand::redo() {
qDebug() << "(Re-)doing the InsertCommand...";
if (m_tableModel) {
m_tableModel->execInsertItems(m_startRow, m_valueList);
}
}

View File

@ -0,0 +1,28 @@
#ifndef INSERTROWSCOMMAND_H
#define INSERTROWSCOMMAND_H
#include <QUndoCommand>
class TableModel;
class InsertRowsCommand : public QUndoCommand {
public:
// TODO don't use simple pointer to model
/// Using simple pointer to model because there was a crash when closing the application with an
/// unclean undo stack
InsertRowsCommand(TableModel* model,
int startRow,
QList<QHash<int, QVariant> > valueList,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo() override;
void redo() override;
private:
TableModel* m_tableModel;
const int m_startRow;
const QList<QHash<int, QVariant> > m_valueList;
};
#endif // INSERTROWSCOMMAND_H

View File

@ -0,0 +1,47 @@
#include "removerowscommand.h"
#include <QDebug>
#include "../tablemodel.h"
RemoveRowsCommand::RemoveRowsCommand(TableModel* model,
const int startRow,
const int nRows,
QUndoCommand* parent)
: QUndoCommand(parent)
, m_tableModel(model)
, m_startRow(startRow) {
qInfo() << "New RemoveCommand...";
const QString commandText =
QString("removing %1 item(s) on position %2").arg(nRows).arg(startRow);
setText(commandText);
for (int row = 0; row < nRows; ++row) {
const int rowPosition = startRow + row;
QModelIndex index = m_tableModel->index(rowPosition, 0);
// TODO use a (static) function "getRoleValueHash" or something
QHash<int, QVariant> values;
values[TableModel::NameRole] = m_tableModel->data(index, TableModel::NameRole);
values[TableModel::DescriptionRole] = m_tableModel->data(index, TableModel::DescriptionRole);
values[TableModel::InfoRole] = m_tableModel->data(index, TableModel::InfoRole);
values[TableModel::AmountRole] = m_tableModel->data(index, TableModel::AmountRole);
values[TableModel::FactorRole] = m_tableModel->data(index, TableModel::FactorRole);
m_valueList.append(values);
}
}
void RemoveRowsCommand::undo() {
qDebug() << "Undoing the RemoveCommand...";
if (m_tableModel) {
m_tableModel->execInsertItems(m_startRow, m_valueList);
}
}
void RemoveRowsCommand::redo() {
qDebug() << "(Re-)doing the RemoveCommand...";
if (m_tableModel) {
m_tableModel->execRemoveItems(m_startRow, m_valueList.length());
}
}

View File

@ -0,0 +1,28 @@
#ifndef REMOVEROWSCOMMAND_H
#define REMOVEROWSCOMMAND_H
#include <QUndoCommand>
class TableModel;
class RemoveRowsCommand : public QUndoCommand {
public:
// TODO don't use simple pointer to model
/// Using simple pointer to model because there was a crash when closing the application with an
/// unclean undo stack
RemoveRowsCommand(TableModel* model,
const int startRow,
const int nRows,
QUndoCommand* parent = nullptr);
/// QUndoCommand interface
void undo() override;
void redo() override;
private:
TableModel* m_tableModel;
const int m_startRow;
QList<QHash<int, QVariant>> m_valueList;
};
#endif // REMOVEROWSCOMMAND_H

40
model/modelitem.cpp Normal file
View File

@ -0,0 +1,40 @@
#include "modelitem.h"
ModelItem::ModelItem(const QHash<int, QVariant> values)
: m_values(values) {}
QVariant ModelItem::data(int role) const { return m_values.value(role); }
bool ModelItem::setData(const QVariant& value, int role) {
bool valueChanged = false;
if (m_values.contains(role)) {
if (m_values.value(role) != value) {
valueChanged = true;
}
}
m_values[role] = value;
return valueChanged;
}
bool ModelItem::setItemData(const QMap<int, QVariant>& changedValues) {
bool valueChanged = false;
QMap<int, QVariant>::const_iterator citer = changedValues.constBegin();
while (citer != changedValues.constEnd()) {
const int role = citer.key();
const QVariant value = citer.value();
if (m_values.contains(role)) {
if (m_values.value(role) != value) {
valueChanged = true;
}
}
m_values[role] = value;
citer++;
}
return valueChanged;
}

19
model/modelitem.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef MODELITEM_H
#define MODELITEM_H
#include <QVariant>
class ModelItem {
public:
ModelItem(const QHash<int, QVariant> values);
QVariant data(int role) const;
bool setData(const QVariant& value, int role);
// TODO change return value to list of changed roles
bool setItemData(const QMap<int, QVariant>& changedValues);
private:
QHash<int, QVariant> m_values;
};
#endif // MODELITEM_H

243
model/tablemodel.cpp Normal file
View File

@ -0,0 +1,243 @@
#include "tablemodel.h"
#include "../formats/jsonparser.h"
#include "commands/edititemcommand.h"
#include "commands/insertrowscommand.h"
#include "commands/removerowscommand.h"
#include "modelitem.h"
QHash<int, QByteArray> TableModel::ROLE_NAMES = {{NameRole, "Name"},
{DescriptionRole, "Description"},
{InfoRole, "Info"},
{AmountRole, "Amount"},
{FactorRole, "Factor"}};
QList<QString> TableModel::intColumns = {"Amount", "Factor"};
TableModel::TableModel(QUndoStack* undoStack, QObject* parent)
: QAbstractTableModel{parent}
, m_undoStack(undoStack) {
for (int row = 0; row < 5; ++row) {
QHash<int, QVariant> values;
values[NameRole] = QString("Item %1").arg(row);
values[DescriptionRole] = QString("This is item %1").arg(row);
values[InfoRole] = QString("Info of item %1").arg(row);
values[AmountRole] = row;
values[FactorRole] = row * 1.1;
shared_ptr<ModelItem> item = make_unique<ModelItem>(values);
m_items.append(std::move(item));
}
}
Qt::ItemFlags TableModel::flags(const QModelIndex& index) const {
return Qt::ItemIsEditable | QAbstractTableModel::flags(index);
}
QHash<int, QByteArray> TableModel::roleNames() const { return ROLE_NAMES; }
int TableModel::rowCount(const QModelIndex& parent) const {
Q_UNUSED(parent);
return m_items.size();
}
int TableModel::columnCount(const QModelIndex& parent) const {
Q_UNUSED(parent);
return ROLE_NAMES.size();
}
QVariant TableModel::data(const QModelIndex& index, int role) const {
const int row = index.row();
const int column = index.column();
if (!index.isValid()) {
return QVariant();
}
if (row >= rowCount(QModelIndex()) || column >= columnCount(QModelIndex())) {
return QVariant();
}
int roleForColumn = getRoleForColumn(column);
switch (role) {
case Qt::DisplayRole:
case Qt::EditRole:
return m_items.at(row)->data(roleForColumn);
case NameRole:
case DescriptionRole:
case InfoRole:
case AmountRole:
case FactorRole:
return m_items.at(row)->data(role);
}
return QVariant();
}
QVariant TableModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (role == Qt::DisplayRole) {
if (orientation == Qt::Horizontal) {
const int columnRole = getRoleForColumn(section);
const QString headerName = ROLE_NAMES.value(columnRole);
return QString("%1").arg(headerName);
} else {
return QString("%1").arg(section);
}
}
return QVariant();
}
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 = getRoleForColumn(column);
return setItemData(index, {{roleForColumn, value}});
}
return false;
}
bool TableModel::setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) {
if (!checkIndex(index)) {
return false;
}
// if (isRoleReadOnly(roleForColumn)) {
// return false;
// }
QMap<int, QVariant> changedValues = onlyChangedValues(index, roles);
if (changedValues.size() > 0) {
EditItemCommand* editCommand = new EditItemCommand(this, index, changedValues);
m_undoStack->push(editCommand);
return true;
}
return false;
}
bool TableModel::removeRows(int firstRow, int nRows, const QModelIndex& parentIndex) {
if (parentIndex != QModelIndex()) {
qWarning() << "Removing of child rows is not supported yet!";
return false;
}
const int lastRow = firstRow + nRows - 1;
if (firstRow < 0 || lastRow >= m_items.size()) {
qWarning() << "Trying to remove rows is out of bounds!";
return false;
}
RemoveRowsCommand* removeCommand = new RemoveRowsCommand(this, firstRow, nRows);
m_undoStack->push(removeCommand);
return true;
}
void TableModel::appendItems(const QByteArray& jsonDoc) { insertItems(-1, jsonDoc, QModelIndex()); }
void TableModel::insertItems(int startPosition,
const QByteArray& jsonDoc,
const QModelIndex& parentIndex) {
qInfo() << "Inserting item(s) into model...";
if (parentIndex != QModelIndex()) {
qWarning() << "Using invalid parent index (no child support for now)";
}
if (startPosition == -1 || startPosition > m_items.size()) {
/// Appending item(s)
startPosition = m_items.size();
}
QList<QHash<int, QVariant>> valueList = JsonParser::toItemValuesList(jsonDoc);
InsertRowsCommand* insertCommand = new InsertRowsCommand(this, startPosition, valueList);
m_undoStack->push(insertCommand);
}
void TableModel::execInsertItems(const int firstRow, const QList<QHash<int, QVariant>> valueList) {
const int nRows = valueList.size();
qDebug() << "Inserting" << nRows << "items...";
const int lastRow = firstRow + nRows - 1;
beginInsertRows(QModelIndex(), firstRow, lastRow);
for (int row = 0; row < nRows; ++row) {
const int rowPosition = firstRow + row;
shared_ptr<ModelItem> item = make_unique<ModelItem>(valueList.at(row));
m_items.insert(rowPosition, std::move(item));
}
endInsertRows();
}
void TableModel::execRemoveItems(const int firstRow, const int nRows) {
const int lastRow = firstRow + nRows - 1;
beginRemoveRows(QModelIndex(), firstRow, lastRow);
m_items.remove(firstRow, nRows);
endRemoveRows();
}
void TableModel::execEditItemData(const int row, const QMap<int, QVariant>& changedValues) {
shared_ptr<ModelItem> item = m_items.at(row);
bool isDataChanged = item->setItemData(changedValues);
if (isDataChanged) {
/// FIXME due to the mapping from roles to the DisplayRole of different columns the complete row
/// is getting notified about (potential) data changes; dataChanged should be called only for
/// the affected columns
const QModelIndex firstIndex = this->index(row, 0);
const QModelIndex lastIndex = this->index(row, ROLE_NAMES.size() - 1);
QList<int> roles = changedValues.keys();
roles.insert(0, Qt::DisplayRole);
emit dataChanged(firstIndex, lastIndex, roles.toVector());
}
}
int TableModel::getRoleForColumn(const int column) const {
switch (column) {
case 0:
return NameRole;
break;
case 1:
return DescriptionRole;
break;
case 2:
return InfoRole;
break;
case 3:
return AmountRole;
break;
case 4:
return FactorRole;
break;
default:
return NameRole;
break;
}
}
QMap<int, QVariant> TableModel::onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const {
QMap<int, QVariant> result;
QMap<int, QVariant>::const_iterator i;
for (i = roleValueMap.constBegin(); i != roleValueMap.constEnd(); ++i) {
const int role = i.key();
const QVariant newValue = i.value();
const QVariant oldValue = index.data(role);
// TODO check if role is a editable role?
if (oldValue != newValue) {
bool emptyValueIsEqualToZero = isEmptyValueEqualToZero(role);
if (emptyValueIsEqualToZero && oldValue == QVariant() && newValue == 0) {
qDebug() << "oldValue:" << oldValue << "& newValue:" << newValue
<< "mean the same. Ignoring...";
continue;
}
qDebug() << "oldValue:" << oldValue << "!= newValue:" << newValue;
result.insert(role, newValue);
} else {
qInfo() << "oldValue is already the same as newValue:" << oldValue << "-> ignoring...";
}
}
return result;
}
bool TableModel::isEmptyValueEqualToZero(const int role) const {
const QString roleName = ROLE_NAMES.value(role);
if (intColumns.contains(roleName)) {
return true;
}
return false;
}

62
model/tablemodel.h Normal file
View File

@ -0,0 +1,62 @@
#ifndef TABLEMODEL_H
#define TABLEMODEL_H
#include <QAbstractTableModel>
class QUndoStack;
class ModelItem;
using namespace std;
class TableModel : public QAbstractTableModel {
Q_OBJECT
friend class InsertRowsCommand;
friend class RemoveRowsCommand;
friend class EditItemCommand;
public:
enum UserRoles { NameRole = Qt::UserRole + 1, DescriptionRole, InfoRole, AmountRole, FactorRole };
static QHash<int, QByteArray> ROLE_NAMES;
static QList<QString> intColumns;
explicit TableModel(QUndoStack* undoStack, QObject* parent = nullptr);
/// QAbstractItemModel interface
Qt::ItemFlags flags(const QModelIndex& index) const override;
QHash<int, QByteArray> roleNames() const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
bool setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) override;
public slots:
// bool insertRows(int position, int rows, const QModelIndex& parentIndex = QModelIndex())
// override;
bool removeRows(int firstRow, int nRows, const QModelIndex& parentIndex = QModelIndex()) override;
void appendItems(const QByteArray& jsonDoc);
void insertItems(int startPosition, const QByteArray& jsonDoc, const QModelIndex& parentIndex);
private:
/// *** members ***
QList<shared_ptr<ModelItem>> m_items;
QUndoStack* m_undoStack;
/// *** functions ***
/// undo/redo functions
void execInsertItems(const int firstRow, const QList<QHash<int, QVariant>> valueList);
void execRemoveItems(const int firstRow, const int nRows);
void execEditItemData(const int row, const QMap<int, QVariant>& changedValues);
/// misc functions
int getRoleForColumn(const int column) const;
QMap<int, QVariant> onlyChangedValues(const QModelIndex& index,
const QMap<int, QVariant>& roleValueMap) const;
bool isEmptyValueEqualToZero(const int role) const;
};
#endif // TABLEMODEL_H