Which database connection is chosen in the second case?
The default database connection is chosen. From QSqlTableModel
's constructor documentation, you can see that if you don't specify a db
argument, it will default to QSqlDatabase()
(which is an empty invalid QSqlDatabase
object):
If db is not valid, the default database connection will be used.
The default connection is defined when calling QSqlDatabase::addDatabase()
without specifying a connectionName parameter.
Do I need an active connection at this point?
Both forms require a valid database connection to be used by the model. You can have a look at the Table Model Example for an example on how to use the class.
Usually, You have to set up the database connection at application startup. After that, you can use this connection in any QSqlQuery
/QSqlQueryModel
/QSqlTableModel
. . .
Should I, instead, do (in the body of the slot - not making model a class member)?
If your goal is just to pass arguments to a member object's constructor, you don't need to allocate the object dynamically. This is a general C++ connection, you can pass whatever arguments you need in your MyClass
's constructor:
class MyClass {
QSqlTableModel model;
public:
MyClass(): model(this, QSqlDatabase::database("mydbconnection")){}
...
Both approaches should do the job. Choosing one over the other does not have to do anything with the select()
call failing. Personally, I would prefer avoiding dynamic allocation if it is not really needed. You can have a look at this question for a similar comparison.
model.select()
returns false
Here are some suggestions that may help figuring out the problem:
Check that the database connection was open()
before constructing the QSqlTableModel
.
Check that you haven't provided a wrong table name in setTable()
.
you can use model.lastError()
to get more information about the error.
qDebug() << model.lastError();