Skip to content Skip to sidebar Skip to footer

Pyqt: How To Handle Event Without Inheritance

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 tut

Solution 1:

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

classWindow(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)

    defeventFilter(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_())

Solution 2:

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

Post a Comment for "Pyqt: How To Handle Event Without Inheritance"