Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 491
Freedom Avatar asked Dec 09 '12 14:12

Freedom


People also ask

What is self Sender () in PyQt5?

You can call self. sender() in a function connected to your button event to get the object that triggered the event. From there you can call the object's objectName() method to get the name. Here's a quick example - the widget has 10 buttons and clicking on a button will update the label's text to show the button name.

What is event filter in PyQt5?

Event Filters For example, dialogs commonly want to filter key presses for some widgets; for example, to modify Return-key handling. The installEventFilter() function enables this by setting up an event filter, causing a nominated filter object to receive the events for a target object in its eventFilter() function.

What is event in Pyqt?

Events in PyQt5 GUI applications are event-driven. Events are generated mainly by the user of an application. But they can be generated by other means as well; e.g. an Internet connection, a window manager, or a timer.


1 Answers

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_())
like image 186
ekhumoro Avatar answered Sep 21 '22 00:09

ekhumoro