Search code examples
pythonpyqtpyqt5qtablewidget

Subclass a widget to override method, while keeping original method functionality


I want to use CTRL+C to copy data from QTableWidget. To do this I have sublclassed QTableWidget and overridden the keyPressEvent() method, which works well. However this looses useful keyPressEvent() functionality such as using direction keys to scroll through the table.

Is there a way to inherent the original method will implementing some additional functionality?

class SubQTableWidget(QtWidgets.QTableWidget):
    def __init__(self, parent=None):
        QtWidgets.QTableWidget.__init__(self, parent)

    def keyPressEvent(self, event):
        # inheret original keyPressEvent() functionality?
        if (event.type() == QtCore.QEvent.KeyPress and
                event.matches(QtGui.QKeySequence.Copy)):
            self.copy_selection()

Solution

  • To override a method you have to understand if it conflicts with the new functionality. In this case the keyPressEvent method of QTableWidget does not conflict with the CTRL+C shorcut since they do nothing by default with that key so to avoid losing the previous functionality then you must call the parent's super method:

    def keyPressEvent(self, event):
        super(SubQTableWidget, self).keyPressEvent(event)
        if event.matches(QtGui.QKeySequence.Copy)):
            self.copy_selection()

    If you want to handle CTRL+C in a simple way then you can use a QShortcut so there is no need to override the keyPressEvent method:

    class SubQTableWidget(QtWidgets.QTableWidget):
        def __init__(self, parent=None):
            super(SubQTableWidget, self).__init__(parent)
            QtWidgets.QShortcut(
                QtGui.QKeySequence(QtGui.QKeySequence.Copy),
                self,
                activated=self.copy_selection,
                context=QtCore.Qt.WidgetShortcut
            )