PySide2 |找出按下了哪个 QKeySequence [英] PySide2 | Finding out which QKeySequence was pressed

查看:66
本文介绍了PySide2 |找出按下了哪个 QKeySequence的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PySide2,我希望有多个执行相同功能的快捷方式,但也取决于按下了哪个键.

I'm using PySide2 and I want to have multiple shortcuts that carry out the same function but also would depend on which key was pressed.

我试图在 QMainWindow 中链接这些函数:

I tried to link the functions as such inside a QMainWindow:

QtWidgets.QShortcut(QtGui.QKeySequence("1"),self).activated.connect(self.test_func)
QtWidgets.QShortcut(QtGui.QKeySequence("2"),self).activated.connect(self.test_func)

这样他们都执行这个函数.

Such that they both execute this function.

def test_func(self, signal):
    print(signal)

希望在按下1"键时会发生 print("1") 并且在按下第二个键时会发生 print("2").当我尝试运行它并按 1 和 2 键时,出现此错误:

Hoping that print("1") happens when the key "1" is pressed and print("2") happens when the second key is pressed. When I tried running this and press the keys 1 and 2, I get this error:

TypeError: test_func() missing 1 required positional argument: 'signal'

我怎样才能做到这一点?

How can I accomplish this?

推荐答案

激活的信号不发送任何信息,所以一个选择是获取发出信号的对象(即 QShortcut)来获取 QKeySequence,然后从后者是字符串:

The activated signal does not send any information so the one option is to obtain the object that emits the signal (ie the QShortcut) to obtain the QKeySequence, and from the latter the string:

from PySide2 import QtCore, QtGui, QtWidgets

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        QtWidgets.QShortcut(QtGui.QKeySequence("1"), self, activated=self.test_func)
        QtWidgets.QShortcut(QtGui.QKeySequence("2"), self, activated=self.test_func)

    @QtCore.Slot()
    def test_func(self):
        shorcut = self.sender()
        sequence = shorcut.key()
        print(sequence.toString())

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

这篇关于PySide2 |找出按下了哪个 QKeySequence的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆