6

How can I handle mouse event without a inheritance, the usecase can be described as follows:

Suppose that I wanna let the QLabel object to handel MouseMoveEvent, the way in the tutorial often goes in the way that we create a new class inherited from QLabel. But can I just use a lambda expression to handel the event without inheritance just like

ql = QLabel()
ql.mouseMoveEvent = lambda e : print e.x(), e.y()

So I do not need to write a whole class and just use simple lambda expression to implement some simple event.

0

2 Answers 2

13

The most flexible way to do this is to install an event filter that can receive events on behalf of the object:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.label = QtGui.QLabel(self)
        self.label.setText('Hello World')
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setFrameStyle(QtGui.QFrame.Box | QtGui.QFrame.Plain)
        self.label.setMouseTracking(True)
        self.label.installEventFilter(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.label)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.label):
            pos = event.pos()
            print('mouse move: (%d, %d)' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())
Sign up to request clarification or add additional context in comments.

1 Comment

especially that installEventFilter(self)
4

Yes you can do this, but in python2 you can't use print in your lambda, as it's a statement and not a function and does not return a value.

Try this:

ql = QLabel()
def event_handler(e):
    print e.x(), e.y()
ql.mouseMoveEvent = event_handler

2 Comments

print is a function in python3 from __future__ import print_function
@X.Jacobs - of course, but from his print-syntax i figured he's using python2. of course a future import is also a solution for python2.6+.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.