Hey all.
I have a Qt5 program that utilizes an Sqlite3 database hooked up to a QSqlTableModel, which is handed to a QTableView. The model is editable via the QTableView with the default submission options (I have to leave focus before changes are committed). However, I needed to intercept changes made in the QTableView and possibly change them, so I created a slot connected to the QSqlTableModel’s beforeUpdate(int,QSqlRecord&) signal.
QSqlDatabase database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("test.sqlite3");
database.open();
QSqlQuery query;
query.exec("CREATE TABLE example (testing text)");
QSqlTableModel *sqlTableModel = new QSqlTableModel(this);
sqlTableModel->setTable("example");
sqlTableModel->select();
sqlTableModel->setHeaderData(0, Qt::Horizontal, tr("Testing"));
connect(sqlTableModel, SIGNAL(beforeUpdate(int,QSqlRecord&)), SLOT(handleBeforeUpdate(int,QSqlRecord&)));
// QTableView
m_ui->tableView->setModel(sqlTableModel);
And the slot:
void MainWindow::handleBeforeUpdate(int row, QSqlRecord &record)
{
Q_UNUSED(row);
record.setValue("testing", "foo");
record.setGenerated("testing", true);
}
Now, to see this for yourself: Insert something into that table. Then double-click it in the QTableView. Edit it, and what I EXPECT to see is instead of that cell in the database being set to whatever you wrote, it’s set to “foo.”
In fact, that IS what happens to the database. However, the QTableView doesn’t show that— it shows a blank row that I can select but do nothing with. If I close the program and reopen it, it shows exactly what I want.
Why isn’t this working? Since the record is pass-by-reference through the signal, shouldn’t it? If not, is there a standard way to intercept edits on the model before it gets to the database without the view getting all screwed up?
I would appreciate any advice!
↧