Items can be added to model dynamically.
This commit is contained in:
@ -1,13 +1,13 @@
|
||||
#include "tablemodel.h"
|
||||
|
||||
#include "../formats/jsonparser.h"
|
||||
#include "modelitem.h"
|
||||
|
||||
enum UserRoles { NameRole = Qt::UserRole + 1, DescriptionRole, InfoRole, AmountRole, FactorRole };
|
||||
static const QHash<int, QByteArray> ROLE_NAMES = {{NameRole, "Name"},
|
||||
{DescriptionRole, "Description"},
|
||||
{InfoRole, "Info"},
|
||||
{AmountRole, "Amount"},
|
||||
{FactorRole, "Factor"}};
|
||||
QHash<int, QByteArray> TableModel::ROLE_NAMES = {{NameRole, "Name"},
|
||||
{DescriptionRole, "Description"},
|
||||
{InfoRole, "Info"},
|
||||
{AmountRole, "Amount"},
|
||||
{FactorRole, "Factor"}};
|
||||
|
||||
TableModel::TableModel(QObject* parent)
|
||||
: QAbstractTableModel{parent} {
|
||||
@ -28,6 +28,8 @@ 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 { return m_items.size(); }
|
||||
|
||||
int TableModel::columnCount(const QModelIndex& parent) const { return ROLE_NAMES.size(); }
|
||||
@ -80,6 +82,31 @@ bool TableModel::setData(const QModelIndex& index, const QVariant& value, int ro
|
||||
|
||||
// bool TableModel::setItemData(const QModelIndex& index, const QMap<int, QVariant>& roles) {}
|
||||
|
||||
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);
|
||||
const int nRows = valueList.size();
|
||||
beginInsertRows(QModelIndex(), startPosition, startPosition + nRows - 1);
|
||||
for (int row = 0; row < nRows; ++row) {
|
||||
const int rowPosition = startPosition + row;
|
||||
shared_ptr<ModelItem> item = make_unique<ModelItem>(valueList.at(row));
|
||||
m_items.insert(rowPosition, std::move(item));
|
||||
}
|
||||
endInsertRows();
|
||||
}
|
||||
|
||||
int TableModel::getRoleForColumn(const int column) const {
|
||||
switch (column) {
|
||||
case 0:
|
||||
|
||||
Reference in New Issue
Block a user