[PyQt] How to override mousePressEvent for an existing QPushButton widget

Dov Grobgeld dov.grobgeld at gmail.com
Thu Jul 30 05:52:40 BST 2009


Hello,

I'm a PyQt/Qt newbie who is trying to port some ideas of mine from (Py)Gtk
to PyQt and I'm having some conceptual problems. The problem that I am
trying to solve is how to add "right click" functionality to a QPushButton
that I received e.g. from the designer. I managed to solve this as follows
when I inherit the widget myself:

class MyButton(QtGui.QPushButton):
    def __init__(self, parent=None):
        QtGui.QPushButton.__init__(self, parent)
        self.setText("Press me")

    def mousePressEvent(self,event):
        if event.button() == QtCore.Qt.LeftButton:
            QtGui.QPushButton.mousePressEvent(self,event)
            return
        print "Processing right click event"

But how would I do the same override in runtime if I all I have is a button
that is a QPushButton? I tried doing:

   button.mousePressEvent = myMousePressEvent

But doing that lead to lots of reference problems with the "self" object,
since the myMousePressEvent is not in the inheritance chain from
QPushButton.

This is actually related to another even more fundamental question, why is
the difference between overriding and connecting? I.e. why is "clicked" a
signal and "mousePressEvent" an overrided virtual. Why can't they both be
signals, in which case the problem I describe wouldn't happen? (That's how
it works in Gtk, btw.)

Thanks in advance!
Dov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.riverbankcomputing.com/pipermail/pyqt/attachments/20090730/743d5990/attachment.html


More information about the PyQt mailing list