hi,
i have subclassed QAbstractTableModel to make a model that works easily with tables that have a primary key. in the beginning i fill a QMap with the contents of the table like this:
void IndexedTableModel
::setTable(QString mtable
) { this->table = mtable;
tableData.clear();
// try to find an index:
QSqlIndex idx
= db.
driver()->primaryIndex
(table
);
Q_ASSERT(idx.count() == 1);
indexColumn = idx.fieldName(0);
QString sql
= "SELECT * FROM " + table;
int row=0;
while (query.next()) {
int idxval = rec.field(indexColumn).value().toInt();
// as the rownumber can be unlike the value of the primary key
// i store the information in a map:
RowContent[row] = idxval;
tableData[row] = rec;
row++;
}
}
void IndexedTableModel::setTable(QString mtable) {
this->table = mtable;
tableData.clear();
// try to find an index:
QSqlIndex idx = db.driver()->primaryIndex (table);
Q_ASSERT(idx.count() == 1);
indexColumn = idx.fieldName(0);
QString sql = "SELECT * FROM " + table;
QSqlQuery query(sql);
int row=0;
while (query.next()) {
QSqlRecord rec = query.record();
int idxval = rec.field(indexColumn).value().toInt();
// as the rownumber can be unlike the value of the primary key
// i store the information in a map:
RowContent[row] = idxval;
tableData[row] = rec;
row++;
}
}
To copy to clipboard, switch view to plain text mode
as long as every cell in the table has a content everything works fine, i read the stuff into the model and can edit it. The problem happens when i come across a row that does not have any data apart from that in the primary key column. i had some debugging input at the end of the above function that assured me that tableData[row].count() is 3 as expected.
but when i try to edit one of the empty cells my function to find the QSqlField for this cell called from setData() bails out:
int row = index.row();
int col = index.column();
int idx = RowContent[row];
qDebug() << "searching for row " << row << " column " << col << " index " << idx;
if (!index.isValid()) {
qDebug() << "..index was invalid ";
}
if (rec.count() <= col) {
qDebug() << "..the record has only " << rec.count() << " columns " << " but you want column " << col;
} else {
return rec.field(col);
}
}
QSqlField IndexedTableModel::FieldToIndex(const QModelIndex &index) {
int row = index.row();
int col = index.column();
int idx = RowContent[row];
qDebug() << "searching for row " << row << " column " << col << " index " << idx;
if (!index.isValid()) {
qDebug() << "..index was invalid ";
return QSqlField();
}
QSqlRecord rec = tableData[idx];
if (rec.count() <= col) {
qDebug() << "..the record has only " << rec.count() << " columns " << " but you want column " << col;
return QSqlField();
} else {
return rec.field(col);
}
}
To copy to clipboard, switch view to plain text mode
will tell me that the record has 0 columns. Anybody knows why?
Bookmarks