How to create PyQt Properties dynamically

后端 未结 2 2069
梦毁少年i
梦毁少年i 2020-12-20 04:29

I am currently looking into a way to create GUI desktop applications with Python and HTML/CSS/JS using PyQt5\'s QWebEngineView.

In my little demo ap

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 04:53

    One way to do this is by using a meta-class:

    class Property(pyqtProperty):
        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):
            self.value = value
            getattr(inst, '_%s_prop_signal_' % 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, Property):
                    continue
                value = attr.value
                notifier = pyqtSignal(type(value))
                attrs[key] = Property(
                    value, key, type(value), notify=notifier)
                attrs['_%s_prop_signal_' % key] = notifier
            return super().__new__(mcs, name, bases, attrs)
    
    class HelloWorldHtmlApp(QWebEngineView):
        ...
        class Backend(QObject, metaclass=PropertyMeta):
            foo = Property('Hello World')
    
            @pyqtSlot()
            def debug(self):
                self.foo = 'I modified foo!'
    

提交回复
热议问题