From Qt Wiki
Revision as of 15:26, 14 January 2015 by Maintenance script (talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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.

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):

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

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.

Example data

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

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.


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.

How the example app looks like

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

Screenshot of the Car Analogy example