Detecting enter on a QLineEdit or QPushButton

QtPython 3.xPyqtKeypressQlineedit

Qt Problem Overview


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)

Qt Solutions


Solution 1 - Qt

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 - Qt

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 - Qt

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionarkero24View Question on Stackoverflow
Solution 1 - Qtuser1006989View Answer on Stackoverflow
Solution 2 - QtrainerView Answer on Stackoverflow
Solution 3 - QtOwlView Answer on Stackoverflow