Skip to content

Instantly share code, notes, and snippets.

@eyllanesc
Last active June 26, 2020 12:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyllanesc/21e1739e25daffb98e4a7d1fad826096 to your computer and use it in GitHub Desktop.
Save eyllanesc/21e1739e25daffb98e4a7d1fad826096 to your computer and use it in GitHub Desktop.
from PySide2.QtCore import Property, QObject, Signal, QCoreApplication, QTimer
class QtProperty(Property):
def __init__(self, value, name='', type_=None, notify=None):
if type_ and notify:
super().__init__(type_, self.getter, self.setter, notify=notify)
self.value = value
self.name = name
def getter(self, inst=None):
return self.value
def setter(self, inst=None, value=None):
if self.value == value:
return
self.value = value
getattr(inst, '%sChanged' % self.name).emit(value)
class PropertyMeta(type(QObject)):
def __new__(mcs, name, bases, attrs):
for key in list(attrs.keys()):
attr = attrs[key]
if not isinstance(attr, QtProperty):
continue
value = attr.value
notifier = Signal(type(value))
attrs[key] = QtProperty(value, key, type(value), notify=notifier)
attrs['%sChanged' % key] = notifier
return super().__new__(mcs, name, bases, attrs)
class BackEnd(QObject, metaclass=PropertyMeta):
my_prop = QtProperty(False)
if __name__ == '__main__':
import sys
app = QCoreApplication(sys.argv)
obj = BackEnd()
obj.my_propChanged.connect(lambda val: print(val))
timer = QTimer()
timer.timeout.connect(lambda: setattr(obj, "my_prop", not getattr(obj, "my_prop")))
timer.start(1000)
sys.exit(app.exec_())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment