Use keyPressEvent to catch enter or return
Asked Answered
E

1

7

I have a simple form with some combos, labels, buttons and a QTextEdit.

I try to catch the enter or return key with keyPressEvent, but for some reason I'm not able to. The ESC key however, that I also use, is recognized.

Here's a piece of the code:

 def keyPressEvent(self, e):
    print e.key()
    if e.key() == QtCore.Qt.Key_Return:
        self.created.setText('return')
    if e.key() == QtCore.Qt.Key_Enter:
        self.created.setText('enter')
    if e.key() == QtCore.Qt.Key_Escape:
        self.cmbEdit = not(self.cmbEdit)
        if self.cmbEdit:

etc...

Am I missing something?

Ephrayim answered 6/12, 2013 at 9:13 Comment(0)
D
8

It's not completely clear from your code, but it looks like you may have reimplemented keyPressEvent for the form, when you needed to do it for the text-edit itself.

One way to fix that is to use an event filter, which can sometimes be more flexible as it avoids having to sub-class the widget(s) you're interested in. The demo script below shows the basics of how to use it. The important thing to note is that the the event-filter should return True to stop any further handling, return False to pass the event on for further handling, or otherwise just drop through to the base-class event-filter.

from PySide import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QTextEdit(self)
        self.edit.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.KeyPress and
            widget is self.edit):
            key = event.key()
            if key == QtCore.Qt.Key_Escape:
                print('escape')
            else:
                if key == QtCore.Qt.Key_Return:
                    self.edit.setText('return')
                elif key == QtCore.Qt.Key_Enter:
                    self.edit.setText('enter')
                return True
        return QtGui.QWidget.eventFilter(self, widget, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 300, 300)
    window.show()
    sys.exit(app.exec_())
Describe answered 6/12, 2013 at 18:48 Comment(1)
That was it! I had to 'attach' it to the textedit, it was reacting to the form events. The idea is to do a SQL update with the textedit's content when enter was pressed.Ephrayim

© 2022 - 2024 — McMap. All rights reserved.