Welcome, guest | Sign In | My Account | Store | Cart

This is a definition of a decorator function that checks which modifier keys are being pressed and adds a keyword argument to a method. This argument is a tuple of names (strings) of the modifier keys that have been pressed when the method was called (or triggered).

Python, 56 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication
import functools

modies = { 'shift': Qt.ShiftModifier,
           'control': Qt.ControlModifier,
           'alt': Qt.AltModifier,
           'meta': Qt.MetaModifier }

def check_modifiers(org_meth):
    """Add modifiers kwarg to a method that contains a tuple of currently pressed modifiers."""

    @functools.wraps(org_meth)
    def wrapper(*args, **kwargs):
        curr = QApplication.keyboardModifiers()
        kwargs['modifiers'] = tuple( name for name, which in modies.items() if curr & which == which )

        org_meth(*args, **kwargs)

    return wrapper


if __name__ == '__main__':

    import sip
    from PyQt4 import QtGui, QtCore

    class MainWindow(QtGui.QMainWindow):

        def __init__(self):
            super(MainWindow, self).__init__()


            centralWidget = QtGui.QWidget(self)
            layout = QtGui.QHBoxLayout(centralWidget)
            self.setCentralWidget(centralWidget)
            self.clickButton = QtGui.QPushButton("click", centralWidget)
            self.clickButton.clicked.connect(self.klick)
            layout.addWidget(self.clickButton)
            self.statusBar()
            self.setFixedWidth(600)

        @check_modifiers
        def klick(self, event, modifiers):
            ms = QtGui.QApplication.keyboardModifiers()
            m = "keyboardModifiers: {1:0=32b} {0} has been pressed"
            self.statusBar().showMessage(m.format(repr(modifiers), int(ms)))
            
    import sys
    app = QtGui.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())

I had to check for pressed modifier keys independently (not for a certain combination) in four different methods. Since this is quiet verbose in PyQt on one hand and on the other I needed to use that information in several different places in the methods it seemed a nice way to put this into a decorator that passes a variable that contains all information needed.

Created by TNT on Wed, 25 Sep 2013 (MIT)
Python recipes (4591)
TNT's recipes (1)

Required Modules

Other Information and Tasks