Important: Please read the Qt Code of Conduct -

How to share database connection parameters between multiple QSqlTableModel objects?

  • When creating a QSqlTableModel object, it asks for a QSqlDatabase parameter in the constructor. If none is given, it goes with a default QSqlDatabase() instance.

    However, suppose that I have created model classes that inherit from QSqlTableModel. I create their respective objects in C++ upon application startup, after configuring my first database connection:

    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
    ModelA model(&app, db);
    ModelB model(&app, db);
    ModelC model(&app, db);

    Then, in my QML files, the user can click a button that will callback to C++ to change the database connection parameters. For example, the callback code could contain:

    QSqlDatabase db = QSqlDatabase::database();

    By using the QSqlDatabase::addDatabase() and QSqlDatabase::database() logic, I would expect that a call to addDatabase would change the connection parameters of all my models, but it doesn't seem to work that way. If I do another call to addDatabase after the application has started up (e.g. when clicking a "Connect" button in QML), my models continue to point to their initial database parameters.

    How can I have my models update their database connection parameters on demand? Do they need to share pointers? Do I need to recreate all the models every time? If I recreate them, will my QML bindings survive? What would the mainstream way of doing this kind of dynamic database configuration?

  • Lifetime Qt Champion


    From the top of my head, I would have a controller class that you connect the QML on and that will re-create the models on the fly and use a signal to notify the QML side that something has changed and they should reload. Some sort of model of models.

  • @SGaist cool! But let me know if I'm overcomplicating things. I'm wondering if it's a good idea to keep model instances around for a long time, like I'm doing. Maybe I should try to make them more "stateless" and create models on the fly as needed.

  • Lifetime Qt Champion

    It depends on how your application should work.

    How many models are you expecting to use ?
    What are the main difference between them ?
    How are you using them ?

  • @SGaist I have 3 or 4 models. The user must be able to dynamically change the database connection parameters via a Settings screen. I've asked this question because I couldn't dynamically update my models' connection parameters.

  • Lifetime Qt Champion

    From the looks of it, you have to re-create the models when you change these settings.