Detecting enter on a QLineEdit or QPushButton

arkero24 picture arkero24 · Mar 22, 2013 · Viewed 45.9k times · Source

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)

Answer

user1006989 picture user1006989 · Mar 22, 2013

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_())