通过 Enter 键调用函数
Call function by Enter key
当 QPushButton ("click") 被 Enter 键盘键按下时,如何使 (on_click) 工作?它只与 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_())
您必须覆盖 keyPressEvent 方法:
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_())
我找到了解决方案:。
你需要覆盖super中的函数class。
MainWindow.keyPressEvent = self.keyPressEvent
当 QPushButton ("click") 被 Enter 键盘键按下时,如何使 (on_click) 工作?它只与 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_())
您必须覆盖 keyPressEvent 方法:
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_())
我找到了解决方案:
你需要覆盖super中的函数class。
MainWindow.keyPressEvent = self.keyPressEvent