Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 890
Maximilien Avatar asked Jan 26 '17 03:01

Maximilien


1 Answers

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.

like image 151
ekhumoro Avatar answered Oct 26 '22 10:10

ekhumoro