Qt for Python UsingQtProperties

From Qt Wiki
Jump to: navigation, search


PySide2 provides a Property function which allows for declaring properties that simultaneously behave both as Qt and Python properties, and have their setters and getters defined as Python functions.

A short example illustrating defining and accessing a Qt property from Python is given below:

 1 from PySide2.QtCore import QObject, Property                                                        
 2                                                                                                     
 3 class MyObject(QObject):                                                                            
 4     def __init__(self,startval=42):                                                                 
 5         QObject.__init__(self)                                                                      
 6         self.ppval = startval                                                                       
 7                                                                                                     
 8     def readPP(self):                                                                                   
 9         return self.ppval                                                                               
10                                                                                                     
11     def setPP(self,val):                                                                                
12         self.ppval = val                                                                                
13                                                                                                     
14     pp = Property(int, readPP, setPP)     
15                                                               
16 obj = MyObject()                                                                                    
17 obj.pp = 47                                                                                         
18 print(obj.pp)

Properties in QML expressions

If you are using properties of your objects in QML expressions, QML requires the property to be NOTIFYable. This can be done using a simple signal:

 1 from PySide2.QtCore import QObject, Signal, Property
 2 
 3 class Person(QObject):
 4     def __init__(self, name):
 5         QObject.__init__(self)
 6         self._person_name = name
 7 
 8     def _name(self):
 9         return self._person_name
10 
11     @Signal
12     def name_changed(self):
13         pass
14 
15     name = Property(str, _name, notify=name_changed)