McLan
McLan

Reputation: 2688

How to delete a row from SQLite database using QSqlQueryModel?

I am trying to delete a row from QSqlQueryModel as follows:

void MainWindow::deleteRecord()
{
    int row_index= ui->tableView->currentIndex().row();
    model->removeRow(row_index);
}

But it is not working.

I tried the following as well:

void MainWindow::deleteRecord()
    {
        int row_index= ui->tableView->currentIndex().row();    
        if(!db_manager->delete_record(QString::number(row_no))){
            ui->appStatus->setText("Error: data deletion ...");
        } else{
            ui->appStatus->setText("Record deleted ...");
        }
    }

Where in db_manager, the function delete_recod(QString row_no) is:

bool DatabaseManager::delete_record(QString row_index)
{
    QSqlQuery query;
    query.prepare("DELETE FROM personal_Info WHERE ref_no =  (:ref_no)");
    query.bindValue(":ref_no",row_index);
    if (!query.exec())
    {
        qDebug() << "Error" << query.lastError().text();
        return false;
    }
    return true;
}

But also not working. In both attempts, the application doesn't crash and no SQLite errors.

What am I doing wrong and how can I fix it?

Upvotes: 0

Views: 2623

Answers (1)

peppe
peppe

Reputation: 22826

The first approach is failing because QSqlQueryModel does not implement removeRows. You're not checking its return value (bad! bad! bad!), which is false, meaning failure.

And how could it possibly implement a row removal function? Your SQL query can be literally anything, including result sets for which it does not make any sense to remove rows.

Instead, consider using a QSqlTableModel -- it or may not apply to your case, but given the form of your DELETE statement, I would say it does. (QSqlTableModel only shows the contets of one table / view).


The second approach is instead possibly working already. The fact you don't see your UI updated does not imply anything at all -- you should check the actual database contents to see if the DELETE statement actually worked and deleted something.

Now note that there's nothing coming from the database telling Qt to update its views. You need to set up that infrastructure. Modern databases support triggers and signalling systems (which are wrapped in Qt by QSqlDriver::notification), which can be used for this purposes. In other cases you msut manually trigger a refresh of your SQL model, for instance by calling QSqlTableModel::select().

Upvotes: 1

Related Questions