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

前端 未结 3 1487
渐次进展
渐次进展 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 05:09

    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 super().eventFilter(obj, event)
    

提交回复
热议问题