PyQt事件,当变量值更改时 [英] PyQt Event when a variable value is changed

查看:506
本文介绍了PyQt事件,当变量值更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量t

t = 0

无论何时更改t值,我都想开始一个事件. 如何 ?没有valuechanged.connect属性或任何变量...

I want to start an event whenever t value is changed. How ? There's no valuechanged.connect properties or anything for variables...

推荐答案

对于全局变量,仅使用赋值是不可能的.但是对于属性来说,它非常简单:只需使用属性(或 __getattr__/__setattr__ ).这样可以有效地将赋值转换为函数调用,使您可以添加所需的任何其他行为:

For a global variable, this is not possible using assignment alone. But for an attribute it is quite simple: just use a property (or maybe __getattr__/__setattr__). This effectively turns assignment into a function call, allowing you to add whatever additional behaviour you like:

class Foo(QWidget):
    valueChanged = pyqtSignal(object)

    def __init__(self, parent=None):
        super(Foo, self).__init__(parent)
        self._t = 0

    @property
    def t(self):
        return self._t

    @t.setter
    def t(self, value):
        self._t = value
        self.valueChanged.emit(value)

现在您可以执行foo = Foo(); foo.t = 5,并且在更改值之后将发出信号.

Now you can do foo = Foo(); foo.t = 5 and the signal will be emitted after the value has changed.

这篇关于PyQt事件,当变量值更改时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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