English 한국어

Using Qt Properties in PySide

PySide 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. class MyObject(QObject):
  2.     def __init__(self,startval=42):
  3.         self.ppval = startval
  4.  
  5.     def readPP(self):
  6.         return self.ppval
  7.  
  8.     def setPP(self,val):
  9.         self.ppval = val
  10.  
  11.     pp = Property(int, readPP, setPP)
  12.  
  13. obj = MyObject()
  14. obj.pp = 47
  15. print obj.pp

The complete specification for PySide’s property system is given in PSEP 103 [pyside.org].

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. class Person(QtCore.QObject):
  2.     def __init__(self, name):
  3.         QtCore.QObject.__init__(self)
  4.         self._person_name = name
  5.  
  6.     def _name(self):
  7.         return self._person_name
  8.  
  9.     @QtCore.Signal
  10.     def name_changed(self): pass
  11.  
  12.     name = QtCore.Property(unicode, _name, notify=name_changed)

Emit the signal when the data changes, and QML will automatically update all expressions depending on the value.

Categories: