How to submit when pressing ENTER on a Qlineedit?

Asked

Viewed 850 times

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 wish I could add that same event by pressing the ENTER key on that QLineEdit.

How can I do that?

My code goes 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 to press ENTER on self.textChat, the method onSubmitText be triggered.

How do I do?

Observing: I’m using Pyqt5, but you’re welcome to have answers with Pyqt4 for future reference.

1 answer

2


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

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

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

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

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

DOCS

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.