PyQt4如何使用方向键触发事件
How to use arrow keys to trigger an event PyQt4
我希望键盘上的箭头键在按下按钮时执行相同的操作。我知道如果我想在单击按钮后连接到 fxn,我会做类似 self.btn.clicked.connect(fxnnamehere) 的事情。我键盘上的箭头键有类似这样的东西吗?
对于这种情况,可以使用 QShortCut
class:
import sys
from PyQt4 import QtCore, QtGui
class Widget(QtGui.QWidget):
def __init__(self):
super().__init__()
QtGui.QShortcut(QtCore.Qt.Key_Up, self, self.fooUp)
QtGui.QShortcut(QtCore.Qt.Key_Down, self, self.fooDown)
QtGui.QShortcut(QtCore.Qt.Key_Left, self, self.fooLeft)
QtGui.QShortcut(QtCore.Qt.Key_Right, self, self.fooRight)
def fooUp(self):
print("up")
def fooDown(self):
print("down")
def fooLeft(self):
print("left")
def fooRight(self):
print("right")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
在您的特定情况下,您似乎正在使用 Qt Designer 生成的代码,class 提供的不是 qwidget,而是用于填充原始小部件的 class .
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
...
QtGui.QShortcut(QtCore.Qt.Key_Up, MainWindow, self.fooUp)
QtGui.QShortcut(QtCore.Qt.Key_Down, MainWindow, self.fooDown)
QtGui.QShortcut(QtCore.Qt.Key_Left, MainWindow, self.fooLeft)
QtGui.QShortcut(QtCore.Qt.Key_Right, MainWindow, self.fooRight)
def fooUp(self):
print("up")
def fooDown(self):
print("down")
def fooLeft(self):
print("left")
def fooRight(self):
print("right")
我希望键盘上的箭头键在按下按钮时执行相同的操作。我知道如果我想在单击按钮后连接到 fxn,我会做类似 self.btn.clicked.connect(fxnnamehere) 的事情。我键盘上的箭头键有类似这样的东西吗?
对于这种情况,可以使用 QShortCut
class:
import sys
from PyQt4 import QtCore, QtGui
class Widget(QtGui.QWidget):
def __init__(self):
super().__init__()
QtGui.QShortcut(QtCore.Qt.Key_Up, self, self.fooUp)
QtGui.QShortcut(QtCore.Qt.Key_Down, self, self.fooDown)
QtGui.QShortcut(QtCore.Qt.Key_Left, self, self.fooLeft)
QtGui.QShortcut(QtCore.Qt.Key_Right, self, self.fooRight)
def fooUp(self):
print("up")
def fooDown(self):
print("down")
def fooLeft(self):
print("left")
def fooRight(self):
print("right")
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
在您的特定情况下,您似乎正在使用 Qt Designer 生成的代码,class 提供的不是 qwidget,而是用于填充原始小部件的 class .
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
...
QtGui.QShortcut(QtCore.Qt.Key_Up, MainWindow, self.fooUp)
QtGui.QShortcut(QtCore.Qt.Key_Down, MainWindow, self.fooDown)
QtGui.QShortcut(QtCore.Qt.Key_Left, MainWindow, self.fooLeft)
QtGui.QShortcut(QtCore.Qt.Key_Right, MainWindow, self.fooRight)
def fooUp(self):
print("up")
def fooDown(self):
print("down")
def fooLeft(self):
print("left")
def fooRight(self):
print("right")