Handling QSqlTableModel data on startup

102 Views Asked by At

I have an application of which I want data from an SQLite database to be parsed directly on startup.

When starting the application, I'm calling a member function of my QSqlTableModel instance called create():

mymodel.cpp

MyModel::MyModel(QObject* parent) : QSqlTableModel(parent)
{
}

// ...

void MyModel::create()
{
    // SQL specific
    createTable();

    setTable(myTableName);
    setSort(2, Qt::DescendingOrder);
    setEditStrategy(QSqlTableModel::OnManualSubmit);

    // config specific
    addUserEntry();

    emit myModelChanged();
};

I have a controller which provides MyModel for QML:

mycontroller.h

class MyController : public QObject
{
    Q_OBJECT
    Q_PROPERTY(MyModel* myModel READ myModel CONSTANT)

    MyModel* myModel() { return _myModel; }

    // ...

private: 
    QSqlDatabase _database;
    MyModel* _myModel { nullptr };
};

mycontroller.cpp

MyController::MyController(QObject* parent) : QObject(parent)
{
    _database = QSqlDatabase::database();
    // ...
    _myModel = new MyModel(this, _database);
}

void MyController::start()
{
    _myModel->create();
    // ...
}

The controller class is being registered for QML in my main.cpp:

main.cpp

int main(int argc, char* argv[])
{
    // ...

    qmlRegisterType<MyController>("my.application.app", 1, 0, "MyController");

    // ...
    _myController->start();

and instantiated in main.qml:

main.qml

ApplicationWindow {
    // ...

    MyController {
        id: myController
        objectName: "myController"

        onMyModelChanged: {
            if (myModel.someValue.length > 0) {
                Config.someValue = myModel.someValue;
            }

            if (myModel.otherValue.length > 0) {
                Config.otherValue = myModel.otherValue;
            }
        }
    }

    // ...

Now, what I want is for my QSqlTableModel to retain data from the SQL table directly after calling the create function so the table model will be refreshed and accessible in QML.

E.g., I want Config.someValue and Config.otherValue in QML to be set directly after starting the application.

How do I tell the QSqlTableModel to refresh and push data to QML even if no data was changed before?

What I can see is when calling QSqlTableModel::data(index(0, 0), 2).toString(), the information is already there, however the table model is not being refreshed in QML but the values requested (i.e. myModel.someValue and myModel.otherValue are shown as undefined. How do I achieve this?

0

There are 0 best solutions below