Maximilien
Maximilien

Reputation: 103

PyQt Event when a variable value is changed

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

Upvotes: 9

Views: 8871

Answers (1)

ekhumoro
ekhumoro

Reputation: 120798

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.

Upvotes: 12

Related Questions