How can I know when the Enter key was pressed on QTextEdit

前端 未结 3 1485
渐次进展
渐次进展 2021-01-23 04:10

I\'m writing Chat gui for client on Python using PyQt5. I have a QTextEdit, which the client can write messages in it. I wan\'t to know when the \'Enter\' key is being pressed w

3条回答
  •  情歌与酒
    2021-01-23 04:46

    When you override keyPressEvent you are listening to the events of the window, instead install an eventFilter to the QTextEdit, not to the window as you have done in your code, and check if the object passed as an argument is the QTextEdit:

    def initUI(self):
        # ...
        self.text_box = QtWidgets.QTextEdit(self)
        self.text_box.installEventFilter(self)
        # ...
    
    def eventFilter(self, obj, event):
        if event.type() == QtCore.QEvent.KeyPress and obj is self.text_box:
            if event.key() == QtCore.Qt.Key_Return and self.text_box.hasFocus():
                print('Enter pressed')
                return True
        return False
    

    This is building upon the answer of @eyllanesc and the problem @Daniel Segal faced. Adding the correct return values as such to the eventFilter solves the problem.

提交回复
热议问题