Is there a way to create an "actual" Qt property in PyQt?
Phil Thompson
phil at riverbankcomputing.com
Thu Oct 22 22:24:48 BST 2020
On 22/10/2020 22:12, Ales Erjavec wrote:
>> ...
>> Note that I don't really care for some further lines in the class
>> definition/constructor; what I'd really prefer is to always have a
>> consistent way to access properties if they *also are* Qt properties.
>
> A while ago I had a similar thought of subverting the property
> descriptor protocol:
>
>
> class Q_Property(pyqtProperty):
> """
> A property descriptor that more closely resembles the
> Q_PROPERTY macro.
>
> Encourage a coding style which is consistent with Qt.
>
> Example:
> >>> class Foo(QObject):
> ... _bar = 0
> ... def bar(self):
> ... return self._bar
> ... def setBar(self, bar):
> ... self._bar = bar
> ... bar = Q_Property(int, fget=bar, fset=setBar)
>
> >>> obj = Foo()
> >>> obj.setBar(2)
> >>> obj.bar()
> 2
> >>> obj.setProperty("bar", 42)
> True
> >>> obj.property("bar")
> 42
> >>> obj.bar()
> 42
> """
> def __get__(self, obj, cls=None):
> # Simply return the contained (bound) fget method
> return self.fget.__get__(obj, cls)
>
> def __set__(self, obj, value):
> raise TypeError
>
> # these do not work
> def setter(self, f):
> raise RuntimeError
>
> def getter(self, f):
> raise RuntimeError
IMHO, that's not a property.
> But have not actually used it anywhere. Usually I just
> use the convention of adding a underscore suffix to the
> property member i.e.
>
> bar_ = pyqtProperty(int, fget=bar, fset=setBar)
Q_PROPERTY is a way of implementing in C++ something that is a property
in QML and Qt Designer. It is not a property in C++.
Python properties are proper properties.
Phil
More information about the PyQt
mailing list