Detecting enter on a QLineEdit or QPushButton

60,425

Solution 1

For the QLineEdit connect to the returnPressed signal.

Alternatively, if you use the setAutoDefault method on your QPushButtons you emit the clicked signal when Enter is pressed on a focused QPushButton:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonOK = QtGui.QPushButton(self)
        self.pushButtonOK.setText("OK")
        self.pushButtonOK.clicked.connect(self.on_pushButtonOK_clicked)
        self.pushButtonOK.setAutoDefault(True)

        self.lineEditNumber = QtGui.QLineEdit(self)
        self.lineEditNumber.returnPressed.connect(self.pushButtonOK.click)
        
        self.layoutHorizontal = QtGui.QHBoxLayout(self)
        self.layoutHorizontal.addWidget(self.pushButtonOK)
        self.layoutHorizontal.addWidget(self.lineEditNumber)

    @QtCore.pyqtSlot()
    def on_pushButtonOK_clicked(self):
        inputNumber = self.lineEditNumber.text()
        if inputNumber.isdigit():
            info = "You selected `{0}`"

        else:
            info = "Please select a number, `{0}` isn't valid!"

        print info.format(inputNumber)

if __name__ == "__main__":
    import sys
    
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')
    
    main = MyWindow()
    main.show()
    
    sys.exit(app.exec_())

Solution 2

QLineEdit will emit the signal returnPressed() whenever the user presses the enter key while in it: http://qt-project.org/doc/qt-4.8/qlineedit.html#signals. You can either connect this signal to your button's click() slot or directly call whatever your button's clicked() signal was connected to.

Solution 3

A slight C++ variation on other answers, it's not significantly different, but I thought i would include it anyway because how you lay things in QT code can be very different from codebase to codebase and I wanted to strip out the extraneous stuff to give the shortest and easiest to understand excerpt of code.

  QLineEdit *TextSend = new QLineEdit("");
  QPushButton *SendPB = new QPushButton("Send!");
  
  connect(TextSend, &QLineEdit::returnPressed, this, &CLITab::SendCommand);
  connect(SendPB, &QPushButton::released, this, &CLITab::SendCommand);

So what this is doing is we create a QLineEdit textbox and a QPushbutton.

We do cosmetic things like set the string label for them and add them to our layout.

Then we setup a callback handler, which will be triggered when the QLineEdit returns "returnPressed", which then calls automatically into a function which i wrote called "CLITab::SendCommand()", and then it's upto this function to extract the data out of QLineEdit and do whatever needs to be done. In practice the TextSend and SendPB pointers would live in the parent class, so that SendCommand() has visibility over these objects.

Just putting this here, along side an example pushbutton, because essentially they work in precisely the same way, all that's different is the signal name emitted.

Share:
60,425

Related videos on Youtube

arkero24
Author by

arkero24

Updated on July 09, 2022

Comments

  • arkero24
    arkero24 almost 2 years

    I've built an app for a game, simple to start. It's a game in which the system randomly chooses a number and a gamer (player) tries to find out the number. Everything is almost done. The app consists of a QLineEdit, a label and three buttons. Once the app tells the player the range of the wanted number, he/she types a bet_number and clicks on the play button. And according to this number he/she gets a message about how close or far the wanted number is away from the bet_number.

    But I find it a little disgusting to click a button. Instead I want to use Enter key to play. So to achieve this, it comes down to specifically two questions:

    1. How could one change to using Enter to play (I mean I need know when QLineEdit detects enter key is pressed)? In this way I'll code properly to point the play method.

    2. If the play button's got the focus, how do you use enter key on this button? (make Button accept Enter key)

  • arkero24
    arkero24 over 11 years
    Thanks for your answer I've got this: connect(self.txtNumGetter, SIGNAL(returnPressed()),self.btnPlayGame,SIGNAL(clicked())); but it doesn't work. Or where must this code line be written?
  • rainer
    rainer over 11 years
    Signals always have to be connected to slots. clicked() is a signal of QPushButton, however, so you cannot connect anything to it---you'd have to use the slot click() instead (without the ending ed).
  • KunMing Xie
    KunMing Xie about 6 years
    void MainWindow::on_password_returnPressed() { ui->go->animateClick(); }
  • Arthur Tacca
    Arthur Tacca over 4 years
    @rainer Just to be pendantic, signals can be connected to other signals. It's just that you won't observe the effect unless you connect that second signal on to a slot (or yet another signal that is connected to a slot, etc.).