Auto-generating-QObject-from-template-in-PySide

From Qt Wiki
Revision as of 14:00, 14 January 2015 by Maintenance script (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.

How to use the Auto-Generator

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

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:

The expected output

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

Categories: