如何检查是否按下了键盘修饰符(Shift、Ctrl 或 Alt)? [英] How can I check if a keyboard modifier is pressed (Shift, Ctrl, or Alt)?

查看:85
本文介绍了如何检查是否按下了键盘修饰符(Shift、Ctrl 或 Alt)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Qt Creator 构建用户界面,我希望按钮执行不同的操作不同的修饰符.所以我想我可以调用具有动态字符串属性的函数,这些函数将根据修饰符执行操作.

I am building a UI with Qt Creator and I want buttons to perform different actions with different modifiers. So I thought I could call functions with dynamic string properties that would perform the action depending on the modifier.

有没有更简单的方法来做到这一点?

Is there a simpler way to do this?

推荐答案

看起来您需要做的就是查看 keyboardModifiers 在您的按钮处理程序中,并根据需要选择不同的操作.各种修饰符可以组合在一起以进行检查对于多键组合:

It looks like all you need to do is check the keyboardModifiers in your button handler, and select a different action as appropriate. The various modifiers can be OR'd together in order to check for multi-key combinations:

PyQt5:

import sys
from PyQt5 import QtCore, QtWidgets

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.button = QtWidgets.QPushButton('Test')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        modifiers = QtWidgets.QApplication.keyboardModifiers()
        if modifiers == QtCore.Qt.ShiftModifier:
            print('Shift+Click')
        elif modifiers == QtCore.Qt.ControlModifier:
            print('Control+Click')
        elif modifiers == (QtCore.Qt.ControlModifier |
                           QtCore.Qt.ShiftModifier):
            print('Control+Shift+Click')
        else:
            print('Click')

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec())

PyQt4:

import sys
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.button = QtGui.QPushButton('Test')
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        modifiers = QtGui.QApplication.keyboardModifiers()
        if modifiers == QtCore.Qt.ShiftModifier:
            print('Shift+Click')
        elif modifiers == QtCore.Qt.ControlModifier:
            print('Control+Click')
        elif modifiers == (QtCore.Qt.ControlModifier |
                           QtCore.Qt.ShiftModifier):
            print('Control+Shift+Click')
        else:
            print('Click')

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

这篇关于如何检查是否按下了键盘修饰符(Shift、Ctrl 或 Alt)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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