From c7e6684fc4e94af967926e4a67794993eea799a1 Mon Sep 17 00:00:00 2001 From: Martin Kleusberg Date: Thu, 11 Apr 2013 14:08:59 +0200 Subject: [PATCH] SqliteTableModel: Allow data() and setData() on rows not cached yet --- src/MainWindow.cpp | 9 +++++++++ src/sqlitetablemodel.cpp | 17 ++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 10d8c5c7..401be01f 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -407,6 +407,15 @@ void MainWindow::deleteRecord() void MainWindow::selectTableLine(int lineToSelect) { + // Are there even that many lines? + if(lineToSelect >= m_browseTableModel->totalRowCount()) + return; + + // Make sure this line has already been fetched + while(lineToSelect >= m_browseTableModel->rowCount() && m_browseTableModel->canFetchMore()) + m_browseTableModel->fetchMore(); + + // Select it ui->dataTable->clearSelection(); ui->dataTable->selectRow(lineToSelect); ui->dataTable->scrollTo(ui->dataTable->currentIndex()); diff --git a/src/sqlitetablemodel.cpp b/src/sqlitetablemodel.cpp index faf54fe7..f1585e5c 100644 --- a/src/sqlitetablemodel.cpp +++ b/src/sqlitetablemodel.cpp @@ -100,20 +100,26 @@ QVariant SqliteTableModel::data(const QModelIndex &index, int role) const if (role == Qt::DisplayRole) { + // If this row is not in the cache yet get it first + while(index.row() >= m_data.size() && canFetchMore()) + const_cast(this)->fetchMore(); // Nothing evil to see here, move along + return m_data.at(index.row()).at(index.column()); - } - else + } else { return QVariant(); + } } bool SqliteTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { if(index.isValid() && role == Qt::EditRole) { - m_data[index.row()].replace(index.column(), value.toByteArray()); - if(m_db->updateRecord(m_sTable, m_headers.at(index.column()), m_data[index.row()].at(0).toInt(), value.toByteArray())) { + // Only update the cache if this row has already been read, if not there's no need to do any changes to the cache + if(index.row() < m_data.size()) + m_data[index.row()].replace(index.column(), value.toByteArray()); + emit(dataChanged(index, index)); return true; } else { @@ -215,7 +221,8 @@ void SqliteTableModel::fetchData(unsigned int from, unsigned to) } } sqlite3_finalize(stmt); - beginInsertRows(QModelIndex(), currentsize + 1, m_data.size()); + + beginInsertRows(QModelIndex(), currentsize, m_data.size()-1); endInsertRows(); }