Skip to content Skip to sidebar Skip to footer

How To Delete Multiple Rows In A Qtableview Widget?

I want to delete rows in a QTableView widget by pressing a QPushButton. The code works fine with a single row, however, when I select multiple rows one row is always left out. This

Solution 1:

Why is always one row not deleted when I select multiple rows and what do I need to change to delete all selected rows?

The problem is caused by removing a row by resetting the positions, for example, say that you remove 3,4,5, first remove 3, then 4 becomes 3, and 5 becomes 4, then you eliminate 4, remove the 4 current so that the initial 4 is not deleted.

QModelIndex are temporary indexes that are not notified if the positions change, instead QPersistentModelIndex if they are notified so you must use them to get the row even if it changes.

def delete(self):
    if self.tableView.selectionModel().hasSelection():
        indexes =[QPersistentModelIndex(index) for index in self.tableView.selectionModel().selectedRows()]
        for index in indexes:
            print('Deleting row %d...' % index.row())
            self.QSModel.removeRow(index.row())
    else:
        print('No row selected!')

How do I automatically select the next row after the deletion is complete so that I could delete the whole table by repeatedly clicking the Delete Row(s) button?

to select a new row you must set some item of that row as active through the setCurrentIndex() method of QTableView, in this example I calculate the last row and with that I get the QPersistentModelIndex of an item of the next row, after deleting I convert it to QModelIndex and I use it in the previous method.

def delete(self):
    if self.tableView.selectionModel().hasSelection():
        indexes =[QPersistentModelIndex(index) for index in self.tableView.selectionModel().selectedRows()]
        maxrow = max(indexes, key=lambda x: x.row()).row()
        next_ix = QPersistentModelIndex(self.QSModel.index(maxrow+1, 0))
        for index in indexes:
            print('Deleting row %d...' % index.row())
            self.QSModel.removeRow(index.row())
        self.tableView.setCurrentIndex(QModelIndex(next_ix))
    else:
        print('No row selected!')

Is there a built-in method that allows me to either connect the QPushButton or its action to DEL/BACKSPACE key-presses? I.e., I want DEL/BACKSPACE key-presses to trigger delete().

to get the keyboard events you must overwrite the keyPressEvent method, this event happens as a QKeyEvent object that has a key method that returns the key pressed, verify if it is the desired key and if it is, then call delete()

def keyPressEvent(self, event):
    ifevent.key() in (Qt.Key_Backspace, Qt.Key_Delete):
        self.delete()
    QDialog.keyPressEvent(self, event)

Post a Comment for "How To Delete Multiple Rows In A Qtableview Widget?"