QSqlTableModel and database closing problem
-
Hello,
how can i disconnect the database from the QSqlTableModel, so that i can close the database without getting warning/errors that the database is still in use?
I have initialized the model
@QSqlDatabase dbq = QSqlDatabase::database(currentDatabase);
QStringList tables = dbq.tables();
tableModel = new QSqlTableModel(0, dbq);
tableModel->setTable(tables[0]);
tableModel->select();
tableView->setModel(tableModel);@and added the model to the TableView. The only way I've found is explicitly deleting the model. Is there a better way?
Code for closing the database:
@
QStringList connections = QSqlDatabase::connectionNames();
if (connections.size() > 0)
{
{
delete tableModel;
QSqlDatabase dbc = QSqlDatabase::database(currentDatabase);
dbc.close();
qDebug() << dbc.lastError();
}
QSqlDatabase::removeDatabase(currentDatabase);
}
@ -
Usually you dont have to use QSqlDatabase::removeDatabase but since when you create a sqlmodel of any type but since you dont specify a parent when you created the QSqlTableModel the model will still exist when you close the program in that case you should destroy the model manually or do the operations with the database with a code like this:
{
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
// Both "db" and "query" are destroyed because they are out of scope
QSqlDatabase::removeDatabase("sales"); // correct -
Try to:
@tableModel->clear();@It clears the model and releases any acquired resource.
http://qt-project.org/doc/qt-5.0/qtsql/qsqlquerymodel.html#clear -
Yes, the database is closed.
@if (QSqlDatabase::connectionNames().size() > 0)
{
{
tableModel->clear();
//delete tableModel;
QSqlDatabase dbc = QSqlDatabase::database(currentDatabase);
dbc.close();
qDebug() << dbc.isOpen();
qDebug() << dbc.lastError();
}
QSqlDatabase::removeDatabase(currentDatabase);
}@output:
@false
QSqlError(-1, "", "")
QSqlDatabasePrivate::removeDatabase: connection '/home/maptuzu/test.db' is still in use, all queries will cease to work.@ -
Have you tried already to delete it manually? You have to delete it once you dont need it anymore since you dont specify it a parent, or you can also put a parent and change it using setParent
-
Make the parent of the QTableModel to be the class where its used, include the following code in its destructor or just before you remove QSqlDatabase::removeDatabase() line. (I have included both QSqlRelationalTableModel and QSqlTableModel just in case you are using both or more than one type of model). Good luck!
foreach(QSqlRelationalTableModel *rmodel, findChildren<QSqlRelationalTableModel *>()) delete rmodel; foreach(QSqlTableModel *tmodel, findChildren<QSqlTableModel *>()) delete tmodel;