如何在 PySide2 中使用箭头键创建快捷方式? [英] How do I make a shortcut using arrow key with PySide2?
问题描述
我想使用 Qt5 + Python (Pyside2) 为按钮添加键盘快捷键.使用普通键创建快捷方式的代码:
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_())
如果我用这个替换 shortcut = ...
行:
If I replace that shortcut = ...
line with this:
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.LeftArrow), self.button)
什么都没发生.我错过了什么?
Nothing happens. What am I missing?
我还尝试将 QtCore.Qt.LeftArrow 值转换为字符串(什么也没发生),并尝试使用 Qt.LeftArrow 直接制作 QShortcut(抱怨 nullptr).使用 QtCore.Qt.Key_Left 作为 QShortcut 的参数也给了我 nullptr.
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.
推荐答案
我发现:
shortcut = QtWidgets.QShortcut(QtGui.QKeySequence.MoveToPreviousChar, self.button)
操作列表在这里:http://doc.qt.io/qt-5/qkeysequence.html#StandardKey-enum
这篇关于如何在 PySide2 中使用箭头键创建快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!