How to check if a key modifier is pressed (shift, ctrl, alt)?

眉间皱痕 提交于 2019-11-27 13:15:13

It looks like all you need to do is check QApplication.keyboardModifiers in your button handler, and select a different action as appropriate:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        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__':

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

(NB: the various modifiers can be OR'd together in order to check for multi-key combinations).

Paul

This is late reply but this is the solution that I found.

I was trying to handle multiple keys pressed at the same time (e.g. A and W or W and D). The solution below works with multiple keys being pressed at the same time (including Ctrl, Shift, Alt, etc). I hope someone else can find it useful.

def keyPressEvent(self, event):
    self.firstrelease = True
    astr = "pressed: " + str(event.key())
    self.keylist.append(astr)

def keyReleaseEvent(self, event):
    if self.firstrelease == True: 
        self.processmultikeys(self.keylist)

    self.firstrelease = False
    del self.keylist[-1]

def processmultikeys(self,keyspressed):
    # your logic here
    print keyspressed

Go here for the original discussion of this solution: How to get multiple key presses in single event?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!