How to submit when pressing ENTER on a QLineEdit?

2

I have a certain QLineEdit in my application that, when a QPushButton is clicked, the text of it is sent to the database.

But I would like to be able to add this same event by pressing ENTER on that QLineEdit .

How can I do this?

My code looks something like this:

 def buildUi(self):

    self.buttonSubmitText  = QtWidgets.QPushButton("Enviar")

    self.textChat = QtWidgets.QLineEdit()

    self.buttonSubmitText.clicked.connect(self.onSubmitText)



 def onSubmitText(self):

    text = self.textChat.text()

    message = create_message(self.selectedUser["id"], text)

    formattedText = self._buildChatText(message)

    self.viewChat.insertHtml(formattedText)

    self.textChat.setText("")

In the above example, I want you to press ENTER on self.textChat , the onSubmitText method fires.

How do I do it?

Note : I'm using Pyqt5, but you'll be welcome to reply with Pyqt4 for future reference.

    
asked by anonymous 24.03.2017 / 12:47

1 answer

2

You can use returnPressed to do this, to connect the event to the method:

...
self.textChat = QtWidgets.QLineEdit()
self.textChat.returnPressed.connect(self.onSubmitText)
...

Or set to trigger a click on buttonSubmitText instead of connecting to the method itself (same effect as ele.click(); in javascript):

...
self.textChat = QtWidgets.QLineEdit()
self.textChat.returnPressed.connect(self.buttonSubmitText.click)
...

In order for the button to visually have that typical effect we know, button to be clicked, you can use animateClick instead of click .

DOCS

From the research I've done I believe it works on Pyqt4 as well.

    
24.03.2017 / 12:54