@davidesalvetti Hmm, I am not very confident in your solution. I would create a helper class to create/use right connection according to current thread.
Something like this (it is just a skeleton, not sure it is working as it is):
#include <QSqlDatabase>
#include <QThread>
class MyBDConnection
{
QString m_dbPath;
QString m_dbName;
Q_DISABLE_COPY(MyBDConnection)
public:
explicit MyBDConnection(const QString &sqlitePath, const QString &cnxName):
m_dbPath(sqlitePath), m_dbName(cnxName)
{}
QSqlDatabase getDBConnection()
{
// Starting with Qt 5.11, sharing the same connection between threads is not allowed.
// Use a dedicated connection for each thread requiring access to the database,
// using the thread address as connection name.
QSqlDatabase cnx;
QString dbName = QStringLiteral("%1_%2").arg(m_dbName).arg(qintptr(QThread::currentThreadId()), 0, 16);
if(QSqlDatabase::contains(dbName))
{
cnx = QSqlDatabase::database(dbName);
}
else
{
cnx = QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), dbName);
cnx.setDatabaseName(m_dbPath);
if (!cnx.isValid() || !cnx.open())
{
qDebug() << "DB connection creation error!";
}
}
return cnx;
}
}
And the only create on instance of this class and pass the pointer to each class which need connection to DB.