8

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

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
Maximilien
  • 93
  • 1
  • 4

1 Answers1

11

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Any suggestions on the modification of your answer where I use a list. See https://stackoverflow.com/q/61695982/8928024 – ZF007 May 09 '20 at 11:26