Kevin_ALA
Kevin_ALA

Reputation: 233

How to remove a row by hitting delete key in QtableWidget?

I would like to delete a row of my Qtablewidget without adding a button and just by hitting the keyboard Delete key. I know, I need to use Key Events but not sure how to assign the even just to the specific tablewidget and the key event wouldnt be activated in the other sections where you have other tabs in the GUI (Long story short: key event just be dedicated to a specific table).

Push button delete style:

for i in rows:
                self.tableWidget.removeRow(i)

Attempt for Key Event:

QtCore.Qt.Key_Delete
QtGui.QTableWidget.keyPressEvent(...,...)

Upvotes: 2

Views: 3907

Answers (1)

Heike
Heike

Reputation: 24440

The easiest way is to subclass QTableWidget and implement your own keyPressEvent, e.g.

import sys
from PyQt5 import QtCore, QtWidgets

class Main(QtWidgets.QTableWidget):

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Delete:
            row = self.currentRow()
            self.removeRow(row)
        else:
            super().keyPressEvent(event)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    main = Main()

    main.setColumnCount(3)
    for i in range(4):
        main.insertRow(main.rowCount())
        for j in range(main.columnCount()):
            main.setItem(i, j, QtWidgets.QTableWidgetItem(f'row {i}, column{j}'))
    main.show()
    sys.exit(app.exec_())

Upvotes: 6

Related Questions