Filling and reading QML UI forms from Python

This PySide tutorial shows you how to create a “classic” form-based UI with the Colibri QML Components and have it filled and controlled by Python code. There are several ways to do this, and depending on your use case, there might be a better method. Please also note that in this example, the controller code knows a bit about the UI (or rather: the UI has to inform the controller which widgets are to be filled), which might not be desired.

CarAnalogy.py

Import the required modules

We need the QtCore module for QObject, the QtGui module for QApplication and the QtDeclarative module for the QML View (QDeclarativeView):

  1. import sys
  2.  
  3. from PySide import QtCore, QtGui, QtDeclarative

Define a Car as QObject

This is simply the Python version of a normal QObject with 4 properties:

  • model (String) – The car name
  • brand (String) – The company who made the card
  • year (int) – The year it was first produced
  • inStock (bool) – If the car is still in stock at the warehouse

  1. class Car(QtCore.QObject):
  2.     def __init__(self, model='', brand='', year=0, in_stock=False):
  3.         QtCore.QObject.__init__(self)
  4.         self.__model = model
  5.         self.__brand = brand
  6.         self.__year = year
  7.         self.__in_stock = in_stock
  8.  
  9.     changed = QtCore.Signal()
  10.  
  11.     def _model(self): return self.__model
  12.     def _brand(self): return self.__brand
  13.     def _year(self): return self.__year
  14.     def _inStock(self): return self.__in_stock
  15.  
  16.     def _setModel(self, model):
  17.         self.__model = model
  18.         self.changed.emit()
  19.  
  20.     def _setBrand(self, brand):
  21.         self.__brand = brand
  22.         self.changed.emit()
  23.  
  24.     def _setYear(self, year):
  25.         self.__year = year
  26.         self.changed.emit()
  27.  
  28.     def _setInStock(self, in_stock):
  29.         self.__in_stock = in_stock
  30.         self.changed.emit()
  31.  
  32.     model = QtCore.Property(str, _model, _setModel, notify=changed)
  33.     brand = QtCore.Property(str, _brand, _setBrand, notify=changed)
  34.     year = QtCore.Property(int, _year, _setYear, notify=changed)
  35.     inStock = QtCore.Property(bool, _inStock, _setInStock, notify=changed)

The controller to fill the form and react to events

This is another QObject that takes a list of cars as constructor parameter. It also remembers the current position in the list of cars. There are three slots that are visible to the “outside” (QML in our case):

  • prev – Go to the previous item
  • next – Go to the next item
  • init – Show the first item

All these slots take a QObject as parameter, and from the QML file, we will pass the root object there, which has a property widgets where we save a dictionary of mappings from name to QML component. The fill function takes care of filling in the data of the current car into the QML widgets.

  1. class Controller(QtCore.QObject):
  2.     def __init__(self, lst):
  3.         QtCore.QObject.__init__(self)
  4.         self._lst = lst
  5.         self._pos = 0
  6.  
  7.     def fill(self, widgets):
  8.         widgets['model'].setProperty('text', self._lst[self._pos].model)
  9.         widgets['brand'].setProperty('text', self._lst[self._pos].brand)
  10.         widgets['year'].setProperty('value', self._lst[self._pos].year)
  11.         widgets['inStock'].setProperty('checked', self._lst[self._pos].inStock)
  12.         widgets['position'].setProperty('text', '%d/%d' % (self._pos+1, len(self._lst)))
  13.  
  14.     @QtCore.Slot(QtCore.QObject)
  15.     def prev(self, root):
  16.         print 'prev'
  17.         self._pos = max(0, self._pos - 1)
  18.         self.fill(root.property('widgets'))
  19.  
  20.     @QtCore.Slot(QtCore.QObject)
  21.     def next(self, root):
  22.         print 'next'
  23.         self._pos = min(len(self._lst) - 1, self._pos + 1)
  24.         self.fill(root.property('widgets'))
  25.  
  26.     @QtCore.Slot(QtCore.QObject)
  27.     def init(self, root):
  28.         print 'init'
  29.         self.fill(root.property('widgets'))

Example data

Here is some example data, so that we can use our example and click through a list of cars:

  1. cars = [
  2.         Car('Model T', 'Ford', 1908),
  3.         Car('Beetle', 'Volkswagen', 1938, True),
  4.         Car('Corolla', 'Toyota', 1966),
  5.         Car('Clio', 'Renault', 1991, True),
  6.         Car('Ambassador', 'Hindustan', 1958),
  7.         Car('Uno', 'Fiat', 1983, True),
  8.         Car('Ibiza', 'Seat', 1984, True),
  9. ]

Putting it all together

We first need to create the controller, which then also knows about our cars. Then, there is some housekeeping that we need to do – create a QApplication, create the QDeclarativeView and set its resizing mode (so that the root object in QML is always as big as the window).

We then get the root context and expose the controller and the cars list to it (if you look closely, we don’t really need the cars themselves). Then, we load the QML file, show the view and start the application.

  1. controller = Controller(cars)
  2.  
  3. app = QtGui.QApplication(sys.argv)
  4.  
  5. view = QtDeclarative.QDeclarativeView()
  6. view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)
  7.  
  8. ctx = view.rootContext()
  9.  
  10. for name in ('controller', 'cars'):
  11.     ctx.setContextProperty(name, locals()[name])
  12.  
  13. view.setSource(__file__.replace('.py', '.qml'))
  14. view.show()
  15.  
  16. app.exec_()

CarAnalogy.qml

This is the user interface of our application. We only use the controller in the UI, and we also only use it for initialization and when buttons are clicked.

  1. import Qt 4.7
  2. import "colibri"
  3.  
  4. Rectangle {
  5.     id: page
  6.  
  7.     property variant widgets
  8.  
  9.     width: 800
  10.     height: 480
  11.  
  12.     Grid {
  13.         id: grid
  14.         columns: 2
  15.         anchors.centerIn: parent
  16.         spacing: 10
  17.  
  18.         Row {
  19.             CLButton { text: "←"; onClicked: { controller.prev(page) } }
  20.             CLButton { text: "→"; onClicked: { controller.next(page) } }
  21.         }
  22.  
  23.         Text { id: position; text: " " }
  24.  
  25.         Text { text: "Model:" }
  26.  
  27.         CLLineEdit { id: model }
  28.  
  29.         Text { text: "Brand:" }
  30.  
  31.         CLLineEdit { id: brand }
  32.  
  33.         Text { text: "Year:" }
  34.  
  35.         Column {
  36.             spacing: 10
  37.             CLSlider {
  38.                 id: year
  39.                 minimum: 1900
  40.                 maximum: 2010
  41.             }
  42.             Text {
  43.                 text: year.value
  44.             }
  45.         }
  46.  
  47.         Text { text: " " }
  48.  
  49.         Row {
  50.             spacing: 10
  51.             CLCheckBox { id: inStock }
  52.             Text { text: "In Stock" }
  53.         }
  54.     }
  55.  
  56.     Component.onCompleted: {
  57.         widgets = {
  58.             'position': position,
  59.             'model': model,
  60.             'brand': brand,
  61.             'year': year,
  62.             'inStock': inStock,
  63.         }
  64.         controller.init(page)
  65.     }
  66. }

How the example app looks like

Simply start the resulting app with python CarAnalogy.py and you should get something like this:

Screenshot of the Car Analogy example

Categories:

  • Tutorial
  • LanguageBindings
  • snippets
  •