Question

While searching for clues on how i can delete multiple rows from QTableView i came across this function: remove selected rows from QTableView

Here is the code:-

   QItemSelection selection( ui.tableView->selectionModel()->selection() );
    QList<int> rows;
    foreach( const QModelIndex & index, selection.indexes() ) {
       rows.append( index.row() );
    }

    qSort( rows );

    int prev = -1;
    for( int i = rows.count() - 1; i >= 0; i -= 1 ) {
       int current = rows[i];
       if( current != prev ) {
          tableModel->removeRows( current, 1 );
          prev = current;
       }
    }

I need help writing the query doing that.I have been trying this:-

query.exec(QString("DELETE FROM %1 id IN %2").arg(tableName,rows));

but i think i should be using QStringList somewhere but i am still reading the QList examples.Anyone?.

Was it helpful?

Solution

Since you seem to be using a QSqlTableModel:

  • in QSqlTableModel::OnFieldChange or OnRowChange modes, removeRows also deletes the records from the database.
  • in QSqlTableModel::OnManualSubmit mode you have to call QSqlTableModel::submitAll() at the end of the loop.

If you were using a QSqlQueryModel, you would have to subclass that model to implement the deletion within removeRows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top