Is there a way to create an "actual" Qt property in PyQt?

Phil Thompson phil at riverbankcomputing.com
Mon Oct 19 14:26:37 BST 2020


On 19/10/2020 02:22, Maurizio Berti wrote:
> We all know that we can create custom QObject properties using the
> `pyqtProperty` function/decorator.
> 
> As far as I know, though, there is a small drawback: those properties 
> do
> not behave "exactly" like other QObject properties: the small (but 
> somehow
> code-wise significant) difference is that PyQt created properties are
> accessible as python properties (self.somePyQtProperty) and not like 
> other
> Qt properties (self.someQtProperty*()*, note the parentheses).

A Qt property is just an entry in the QMetaObject that calls ordinary 
getter and setter functions. The point of them is to implement 
property-like behaviour for QML and Designer (but *not* for C++). 
pyqtProperty creates properties that behave in exactly the same way with 
the advantage that they also behave as properties for Python. The only 
difference is that with Qt property names are defined in a different 
namespace to their getters and setters and so may have the same name as 
the getter (or setter if you are feeling perverse). With Python the 
property names and the getters and setter are defined in the same 
namespace (ie. the class dictionary).

> I know that this might seem trivial, but it's something that has 
> slightly
> buggered me for some amount of time, mostly because I often use the 
> QObject
> constructor to automatically set properties.
> 
> From the basic code perspective it's not that an issue: I could set a
> custom property to _someProperty and then create the related 
> someProperty()
> and setSomeProperty(value) functions for "readability" reasons, but 
> since
> I'm using some custom made plugins in designer I'd prefer to keep 
> property
> names as clean as possible there too.
> Obviously, using def someProperty(self): after the property declaration 
> is
> not an option, as it would make property access unavailable.
> 
> 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.
> 
> So, the question: is there a way or workaround to allow creating a Qt
> property on PyQt that is still accessible using the self.property() 
> syntax,
> while keeping the property name intact?

The property, the getter and the setter must all have different names 
(assuming you want to use each of those names). Use the fget and fset 
arguments to pyqtProperty() explicitly specify the getter and setter 
names.

Phil


More information about the PyQt mailing list