PySide keyPressEvent catches input or return

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

I am trying to catch an enter or return key using keyPressEvent, but for some reason I cannot. However, the ESC key that I also use is recognized.

Here is the code snippet:

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...

Did I miss something?

+6
source share
1 answer

This is not entirely clear from your code, but it looks like you could override keyPressEvent for the form when you needed to do this for the text editing itself.

One way to fix this is to use an event filter, which can sometimes be more flexible, since it avoids subclassing the widget (s) Interesting. The demo below the script shows the basics of use. It is important to note that the event filter must return True to stop any further processing, return False to pass the event for further processing, or else just go 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_()) 
+7
source

Source: https://habr.com/ru/post/959452/


All Articles