PyQt Event when a variable value is changed

给你一囗甜甜゛ 提交于 2020-08-07 05:19:31

问题


I have a variable t

t = 0

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


回答1:


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)

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



来源:https://stackoverflow.com/questions/41865287/pyqt-event-when-a-variable-value-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!