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

前端 未结 3 1518
渐次进展
渐次进展 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

    The answer from @eyllanesc is very good if you are determined to use QTextEdit.

    If you can get away with QLineEdit and its limitations, you can use the returnPressed() signal. The biggest drawback for QLineEdit is you are limited to one line of text. And there is no word wrap. But the advantage is you don't have to mess with eventFilters or think too hard about how keyPress signals fall through all of the widgets in your app.

    Here is a minimal example that copies from one QLineEdit to another:

    import sys
    
    from PyQt5.QtWidgets import * 
    
    
    class PrintWindow(QMainWindow):
    
        def __init__(self):
            super().__init__()
            self.left=50
            self.top=50
            self.width=300
            self.height=300
            self.initUI()
    
        def initUI(self):
    
            self.setGeometry(self.left,self.top,self.width,self.height)
    
            self.line_edit1 = QLineEdit(self)
            self.line_edit1.move(50, 50)
            self.line_edit1.returnPressed.connect(self.on_line_edit1_returnPressed)
    
            self.line_edit2 = QLineEdit(self)
            self.line_edit2.move(50, 100)
    
            self.show()
    
        def on_line_edit1_returnPressed(self):
            self.line_edit2.setText(self.line_edit1.text())
    
    if __name__ == '__main__':
    
        app = QApplication(sys.argv)
        window = PrintWindow()
        sys.exit(app.exec_())
    

    In this example, I have manually connected to the signal in line 22 (self.line_edit1.returnPressed.connect). If you are using a ui file, this connection can be left out and your program will automatically call the on__returnPressed method.

提交回复
热议问题