[PyQt] Intro and question

dboddie at trolltech.com dboddie at trolltech.com
Mon Dec 1 19:21:50 GMT 2008

On Mon Dec 1 18:24:38 GMT 2008, Christian Aubert wrote:

> Right, this is a keyboard shortcut. I'm looking for a modifier that
> applies to the mouse click, so that when your ctrl-click or alt-click or
> right-click, the button has a different behavior.

The signal that tells you when the button has been clicked doesn't carry this
kind of information, unfortunately. However, you can create a subclass that
emits a signal with the state of the modifier keys:

from PyQt4.QtCore import Qt, SIGNAL
from PyQt4.QtGui import *

class KeyButton(QPushButton):
    def __init__(self, *args):
        QPushButton.__init__(self, *args)
        self.modifiers = Qt.NoModifier
        self.connect(self, SIGNAL("clicked()"), self.handleClick)
    def mousePressEvent(self, event):
        self.modifiers = event.modifiers()
        QPushButton.mousePressEvent(self, event)
    def handleClick(self):
        self.emit(SIGNAL("clicked(Qt::KeyboardModifiers)"), self.modifiers)

Basically, the mousePressEvent() method handles the low-level event for mouse
button presses and records the state of the modifier keys, but passes the
event on to the base class's implementation so that the button behaves

In the __init__() method, we connected the button's standard clicked() signal
to a new handleClick() method, where we emit our own signal. The rest of the
code shows how you could use it:

app = QApplication([])

def fn(modifiers):
    if modifiers & Qt.ShiftModifier:
        print "Shift"
    if modifiers & Qt.ControlModifier:
        print "Ctrl"
    if modifiers & Qt.AltModifier:
        print "Alt"

button = KeyButton("Click me")

button.connect(button, SIGNAL("clicked(Qt::KeyboardModifiers)"), fn)

Good luck!


More information about the PyQt mailing list