Mobile: Map directly from source in DiveListSortModel::getIdxForId()

Instead of looping over all dives and search the dive with the given
id, let the source model determine the index and map that. Thus,
we do only one mapping and don't generate a ton of DiveObjectHelpers.

Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
This commit is contained in:
Berthold Stoeger 2019-08-13 21:31:53 +02:00 committed by bstoeger
parent 62f1a92068
commit 20e847f9d8
2 changed files with 16 additions and 7 deletions

View file

@ -62,13 +62,12 @@ int DiveListSortModel::shown()
int DiveListSortModel::getIdxForId(int id) int DiveListSortModel::getIdxForId(int id)
{ {
for (int i = 0; i < rowCount(); i++) { DiveListModel *mySourceModel = qobject_cast<DiveListModel *>(sourceModel());
QVariant v = data(index(i, 0), DiveListModel::DiveRole); QModelIndex sourceIdx = mySourceModel->getDiveQIdx(id);
DiveObjectHelper d = v.value<DiveObjectHelper>(); if (!sourceIdx.isValid())
if (d.id() == id)
return i;
}
return -1; return -1;
QModelIndex localIdx = mapFromSource(sourceIdx);
return localIdx.row();
} }
void DiveListSortModel::reload() void DiveListSortModel::reload()
@ -187,11 +186,20 @@ int DiveListModel::rowCount(const QModelIndex &) const
return dive_table.nr; return dive_table.nr;
} }
// Get the index of a dive in the global dive list by the dive's unique id. Returns an integer [0..nrdives).
int DiveListModel::getDiveIdx(int id) const int DiveListModel::getDiveIdx(int id) const
{ {
return get_idx_by_uniq_id(id); return get_idx_by_uniq_id(id);
} }
// Get an index of a dive. In contrast to getDiveIdx, this returns a Qt model-index,
// which can be used to access data of a Qt model.
QModelIndex DiveListModel::getDiveQIdx(int id)
{
int idx = getDiveIdx(id);
return idx >= 0 ? createIndex(idx, 0) : QModelIndex();
}
QVariant DiveListModel::data(const QModelIndex &index, int role) const QVariant DiveListModel::data(const QModelIndex &index, int role) const
{ {
if(index.row() < 0 || index.row() >= dive_table.nr) if(index.row() < 0 || index.row() >= dive_table.nr)

View file

@ -58,6 +58,7 @@ public:
struct dive *getDive(int i); struct dive *getDive(int i);
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const;
int getDiveIdx(int id) const; int getDiveIdx(int id) const;
QModelIndex getDiveQIdx(int id);
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QHash<int, QByteArray> roleNames() const; QHash<int, QByteArray> roleNames() const;
QString startAddDive(); QString startAddDive();