Hello!
Added to the model line (which have not yet saved) are normally removed. And those who were already in the database, it seems not removed but only marked for deletion, and self-deletion occurs after the call submitAll(). Source code examples in attachment.
Is there any way to delete rows from the model without invoking submitAll()?
#include <QtCore/QCoreApplication>
#include <QtSql>
bool createConnection()
{
db.setDatabaseName("test.sqlite");
if (!db.open())
return false;
return true;
}
// Create a table and populate it with test data
void createFakeData()
{
query.exec("DROP TABLE users");
query.exec("CREATE TABLE users ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL DEFAULT '')");
query.exec("INSERT INTO users (name) VALUES ('john')");
query.exec("INSERT INTO users (name) VALUES ('bill')");
}
int main(int argc, char *argv[])
{
if (!createConnection())
return 1;
createFakeData();
model.setTable("users");
model.select();
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 2
qDebug() << "insertRow()";
int row = model.rowCount();
model.insertRow(row);
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 3
qDebug() << "removeRow()";
model.removeRow(row);
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 2
qDebug() << "removeRow()";
model.removeRow(row-1);
qDebug() << "! rowCount:" << model.rowCount(); // rowCount: 2 (!)
qDebug() << "\nsubmitAll()";
model.submitAll();
qDebug() << "! rowCount:" << model.rowCount(); // rowCount: 1
return a.exec();
}
#include <QtCore/QCoreApplication>
#include <QtSql>
bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.sqlite");
if (!db.open())
return false;
return true;
}
// Create a table and populate it with test data
void createFakeData()
{
QSqlQuery query;
query.exec("DROP TABLE users");
query.exec("CREATE TABLE users ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL DEFAULT '')");
query.exec("INSERT INTO users (name) VALUES ('john')");
query.exec("INSERT INTO users (name) VALUES ('bill')");
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
if (!createConnection())
return 1;
createFakeData();
QSqlTableModel model;
model.setTable("users");
model.setEditStrategy(QSqlTableModel::OnManualSubmit);
model.select();
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 2
qDebug() << "insertRow()";
int row = model.rowCount();
model.insertRow(row);
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 3
qDebug() << "removeRow()";
model.removeRow(row);
qDebug() << "rowCount:" << model.rowCount(); // rowCount: 2
qDebug() << "removeRow()";
model.removeRow(row-1);
qDebug() << "! rowCount:" << model.rowCount(); // rowCount: 2 (!)
qDebug() << "\nsubmitAll()";
model.submitAll();
qDebug() << "! rowCount:" << model.rowCount(); // rowCount: 1
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks