PDA

View Full Version : Strange things happening to QSqlTableModel (while inserting, deleting, updating)



Charlie42
17th July 2015, 08:52
model = new QSqlTableModel(this, db1);
model->setTable("subjects");
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->select();
model->removeColumn(0); // don't show the ID
ui->tableView->setModel(model);
Inserting:

model->insertRow(0);
Deleting:

QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
if (selection.count())
{
for (int i = 0; i < selection.count(); i++)
{
QModelIndex index = selection.at(i);
qDebug() << index.row();
qDebug() << model->removeRow(selection.at(i).row());
model->select();
qDebug() << model->lastError();
//model->submitAll();
}
//model1->submitAll();
}

So, the table displays correctly.
When I edit a cell, the row gets empty and shows !, like it was deleted. Nothing changes in DB.
When I delete a row with algorithm above, removeRow returns true, the table view blinks like it's re-rendering, but nothing changes.
When I insert a row, edit it, it gets empty and shows !, BUT it appears in DB and it's in the table when I reopen the app.
When I un-comment model->submitAll(); nothing changes.
Any ideas?

anda_skoa
17th July 2015, 10:31
The deletion code is definitely wrong.
After the first modification all model indexes become invalid, so the loop continues with model indexes that are no longer appropriate.
It also reloads the data before submitting the change, that looks problematic to me as well.

Also the removal of a column looks strange. Did you want to use QTableView::setColumnHidden?

Cheers,
_

Charlie42
17th July 2015, 11:49
Also the removal of a column looks strange. Did you want to use QTableView::setColumnHidden?
It works now, thank you!
I was 100% sure I took that part from the docs but now I see it's

view->hideColumn(0); // don't show the ID
Anyway, thank you very much.

Added after 33 minutes:

I celebrated too soon, it fixed everything except:

When I insert a row, edit it, it gets empty and shows !, BUT it appears in DB and it's in the table when I reopen the app.