Search code examples
pythonpyqtpyqt5qtableviewqkeyevent

PyQt QTableView - Capture KeyDown / KeyPress Event


I would like to capture a Key Down Event on a QTableView. I would also like to determine, if it was a keydown on DEL button, my QTableView is created like this (from QtCreator):

self.tblview_data_sources = QtWidgets.QTableView(self.groupBox_2)
self.tblview_data_sources.setGeometry(QtCore.QRect(10, 20, 721, 121))
self.tblview_data_sources.setObjectName("tblview_data_sources")

If it is in fact a DEL-Keydown I would like to revmove the row which is selected at the moment.

QTableView has this method keyPressEvent which needs a QKeyEvent - how do I get this Event?


Solution

  • For your case, you have the following possible solutions:

    1. keyPressEvent: use the keyPressEvent method but for this you must create a class that inherits from QTableView and overwrite that method.

    class TableView(QtWidgets.QTableView):
        def keyPressEvent(self, event):
            if event.key() == QtCore.Qt.Key_Delete:
                print("DELETE")
            super(TableView, self).keyPressEvent(event)
    ...
    
    def setupUi(self, SOME):
         ...
         self.tblview_data_sources = TableView(self.groupBox_2) # change QtWidgets.QTableView to TableView
    
    1. eventFilter: Use eventFilter and for this you must use installEventFilter but for this your class must inherit from some class that inherits from QObject, and if you are using Qt Designer the class is not, which also involves many lines of code so I will omit the example.

    2. QShortcut: And my preferred solution for its simplicity, use QShortcut:


        QtWidgets.QShortcut(QtCore.Qt.Key_Delete, self.tblview_data_sources, activated=self.someSlot)
        ...
    def someSlot(self):
        print("DELETE")