Auto-generating QObject from template in PySide

In the previous PySide tutorial, we have defined a QObject subclass “Car” with 4 properties which took about 36 lines of code. The code is repetitive, and it follows a scheme – every property has a getter, setter and notification method (in the case of the previous example, we shared the notification signal amongst all properties). For a very generic “entity” QObject, there is an easier way: Auto-generating the QObject from a template that specifies the names of the properties and the type of each property. Attributes, getters, setters and notification methods are automatically generated, and the object can be used as if it was a normal Python object.

The Auto-Generator function

This function gets one or more class_def tuples (length: two) that specify the name and the type of objects (see below for an example). The only optional keyword at the moment is “name”, which specifies the name of the class for debugging purposes.

  1. from PySide import QtCore
  2.  
  3. def AutoQObject(*class_def, **kwargs):
  4.     class Object(QtCore.QObject):
  5.         def __init__(self, **kwargs):
  6.             QtCore.QObject.__init__(self)
  7.             for key, val in class_def:
  8.                 self.__dict__['_'+key] = kwargs.get(key, val())
  9.  
  10.         def __repr__(self):
  11.             values = ('%s=%r' % (key, self.__dict__['_'+key]) \
  12.                     for key, value in class_def)
  13.             return '<%s (%s)>' % (kwargs.get('name', 'QObject'), ', '.join(values))
  14.  
  15.         for key, value in class_def:
  16.             nfy = locals()['_nfy_'+key] = QtCore.Signal()
  17.  
  18.             def _get(key):
  19.                 def f(self):
  20.                     return self.__dict__['_'+key]
  21.                 return f
  22.  
  23.             def _set(key):
  24.                 def f(self, value):
  25.                     self.__dict__['_'+key] = value
  26.                     self.__dict__['_nfy_'+key].emit()
  27.                 return f
  28.  
  29.             set = locals()['_set_'+key] = _set(key)
  30.             get = locals()['_get_'+key] = _get(key)
  31.  
  32.             locals()[key] = QtCore.Property(value, get, set, notify=nfy)
  33.  
  34.     return Object

How to use the Auto-Generator

Taking the example of our previous tutorial, defining a “Car” object has become quite easy now:

  1. Car = AutoQObject(
  2.     ('model', str),
  3.     ('brand', str),
  4.     ('year', int),
  5.     ('inStock', bool),
  6.     name='Car'
  7. )

The amount of lines has decreased from 36 to 7 (if you ignore the fact that AutoQObject does also take some lines). The definition is more straightforward, and it saves you a lot of typing and errors compared to if you were to do it manually.

Example usage of our generated class

We could simply drop this code into the previous tutorial example and see that it still works. We just do some basic instantiation and reading of the values to see if it works:

  1. print Car
  2.  
  3. c = Car(model='Fiesta', brand='Ford', year=1337)
  4. print c.model, c.brand, c.year, c.inStock
  5. print c
  6.  
  7. c.inStock = True
  8.  
  9. print c.model, c.brand, c.year, c.inStock
  10. print c

The expected output

If everything works as planned, this is what you should get as output when running the example code:

  1. <class '__main__.Object'>
  2. Fiesta Ford 1337 False
  3. <Car (model='Fiesta', brand='Ford', year=1337, inStock=False)>
  4. Fiesta Ford 1337 True
  5. <Car (model='Fiesta', brand='Ford', year=1337, inStock=True)>

Categories:

  • Tutorial
  • LanguageBindings
  • snippets
  •