apelliciari apelliciari - 5 months ago 30
Python Question

PyQt: how to receive keyboard events in a subclassed QWidget?

Maybe this is been asked many times, but i can't find a solution.

I have a dialog:

class PostDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog() #code from designer!!
self.ui.setupUi(self)

self.ui.plainTextEdit = ContentEditor()


This dialog has a QPlainTextEdit from the designer.

I need to override keyPress and keyRelease of that QPlainTextEdit.

So i have subclassed it:

class ContentEditor(QtGui.QPlainTextEdit):

def __init__(self, parent=None):
QtGui.QPlainTextEdit.__init__(self, parent)

def keyPressEvent(self, event):
print "do something"


but ContentEditor.keyPressEvent is never called! Why?

Answer

I recommend using installEventFilter for this purpose:

This would look like:

class PostDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.ui = Ui_Dialog() #code from designer!!
        self.ui.setupUi(self)

        self.ui.plainTextEdit.installEventFilter(self)

    def eventFilter(self, event):
        if event.type() == QtCore.QEvent.KeyPress:
            # do some stuff ...
            return True # means stop event propagation
        else:
            return QtGui.QDialog.eventFilter(self, event)
Comments