Atheer
Atheer

Reputation: 921

Call function by Enter key

How can I make (on_click) works when QPushButton ("click") is pressed by Enter keyboard key? it only interacts with mouse_click

import sys
from PyQt5.QtWidgets import *

class Example(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.label = QLabel("",self)
        self.label.move(100, 100)

        self.button = QPushButton('click', self)
        self.button.move(100, 50)
        self.button.clicked.connect(self.on_click)

        self.setGeometry(500, 150, 200, 200)
        self.show()    

    def on_click(self):
        self.label.setText("Hello")

if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = Example()
   sys.exit(app.exec_())

Upvotes: 1

Views: 4406

Answers (2)

yinwu33
yinwu33

Reputation: 1

I found a solution regarding this: keyPressEvent() method doesn't work for PyQt5 / Python 3+.

You need to override the function in super class.

MainWindow.keyPressEvent = self.keyPressEvent

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 244301

You have to overwrite the keyPressEvent method:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Example(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.label = QLabel("",self)
        self.label.move(100, 100)

        self.button = QPushButton('click', self)
        self.button.move(100, 50)
        self.button.clicked.connect(self.on_click)

        self.setGeometry(500, 150, 200, 200)
        self.show()    

    def on_click(self):
        self.label.setText("Hello")

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Return:
            self.on_click()


if __name__ == '__main__':
   app = QApplication(sys.argv)
   ex = Example()
   sys.exit(app.exec_())

Upvotes: 3

Related Questions