问题
I want to add a keyboard shortcut to a button with Qt5 + Python (Pyside2). Code for making a shortcut with a regular key:
import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",\
"Hola Mundo", "Привет мир"]
self.button = QtWidgets.QPushButton("Click me!")
self.text = QtWidgets.QLabel("Hello World")
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.text.setFont(QtGui.QFont("Titillium", 30))
self.button.setFont(QtGui.QFont("Titillium", 20))
self.layout = QtWidgets.QVBoxLayout()
self.layout.addWidget(self.text)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence('o'), self.button)
shortcut.activated.connect(self.magic)
self.button.clicked.connect(self.magic)
def magic(self):
self.text.setText(random.choice(self.hello))
if __name__ == "__main__":
app = QtWidgets.QApplication([])
widget = MyWidget()
widget.resize(800, 600)
widget.show()
sys.exit(app.exec_())
If I replace that shortcut = ...
line with this:
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.LeftArrow), self.button)
Nothing happens. What am I missing?
I also tried converting the QtCore.Qt.LeftArrow value to string (nothing happens), and tried making the QShortcut directly with the Qt.LeftArrow (complains about nullptr). Using QtCore.Qt.Key_Left as parameter for QShortcut gave me nullptr too.
回答1:
I found out:
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence.MoveToPreviousChar, self.button)
The list of actions are here: http://doc.qt.io/qt-5/qkeysequence.html#StandardKey-enum
回答2:
With PySide2 something like the following should works:
QtWidgets.QShortcut(QtGui.QKeySequence("right"), self.button, self.magic)
which will directly connect the button with callback function.
来源:https://stackoverflow.com/questions/50736014/how-do-i-make-a-shortcut-using-arrow-key-with-pyside2