Qt World Summit: Register Today!

Update QSqlTableModel after QSqlQuery executing

  • Hi!
    I want to update my QSqlTableModel and tableView after I create a select distinct for filtering the database.
    My database consist a column ("should_alarm") that I want to filter on and only show when the value is '1'.

    My code is like this:

    // Connect the database
    void MainWindow::on_pushButton_ConnectDatabase_clicked()
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(".\\Data copy 14-12-2015 Test1\\database.db3");
        if (db.open()) {
          qDebug() << "SQL database is connected.";
        } else {
          qDebug() << "ERROR: SQL database is NOT connected.";
        model = new QSqlTableModel(this, db);
    // Test button for start the filtering
    void MainWindow::on_pushButton_testFilter_clicked()
        QSqlDatabase db = QSqlDatabase::database();
        QSqlQuery query(db);
        query->exec("SELECT * FROM datalog WHERE should_alarm=1");
        model.submitAll(); // Not sure about how to "update" the model and tableView

    The problem is that the tableView doesn't update the view after the filtering. I don't know how the update process works, so I hope some one can help me.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    You are currently just running that query, it doesn't modify anything in your model. You should use the setFilter function for QSqlTableModel, to do the filtering you want.

  • Is it posible you can give me an example of setFilter @SGaist ?
    That would be great!

  • Lifetime Qt Champion

    Adapted from the documentation example: model->setFilter("should_alarm=1");