PyQt Event when a variable value is changed
Asked Answered
A

1

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

Asperity answered 26/1, 2017 at 3:4 Comment(0)
V
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.

Verrazano answered 26/1, 2017 at 5:39 Comment(1)
Any suggestions on the modification of your answer where I use a list. See https://mcmap.net/q/1327289/-how-to-apply-pyqt5-event-on-a-list-with-values-instead-of-single-variable-value-closed/8928024Candlemas

© 2022 - 2024 — McMap. All rights reserved.