PyQt:如何处理没有继承的事件 [英] PyQt: how to handle event without inheritance

查看:133
本文介绍了PyQt:如何处理没有继承的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我没有继承,我可以处理鼠标事件,这个用法可以描述如下:

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

假设我想让QLabel对象来处理$ code> MouseMoveEvent ,教程中的方式通常会阻碍我们创建一个继承自QLabel的新类。但是我可以使用lambda表达式来处理事件而不继承,就像

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

所以我不需要写一个整个类,只需使用简单的lambda表达式来实现一些简单的事件。

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

推荐答案

最灵活的方法是安装可以代表对象接收事件的事件过滤器

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

这篇关于PyQt:如何处理没有继承的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆