Selectable list of Python objects in QML

This PySide code example shows you how to display a list of arbitrary Python objects in QML and to get the “real” Python object in a callback when the user clicks on a list item. This is done by wrapping the Python objects inside a QObject. Of course, if you are developing a new application, you can create your model entity objects directly as QObject subclasses, but for adding a QML UI on top of existing Python code, this should be very useful.

This example consists of two files:

  • PythonList.py – Our Python code
  • PythonList.qml – The corresponding QML UI

PythonList.py

This is the main module. After finishing writing it, you can start it using python PythonList.py

Import the required modules

This is pretty straightforward. If you don’t have OpenGL support on your target platform (or you don’t want to use OpenGL-accelerated QML), simply remove the line from PySide import QtOpenGL.

  1. import sys
  2.  
  3. from PySide import QtCore
  4. from PySide import QtGui
  5. from PySide import QtDeclarative
  6. from PySide import QtOpenGL

Define a simple QObject wrapper

Create a new QObject subclass that gets your custom Python object (called “thing” in this example) as constructor parameter. You can then define different properties (QtCore.Property) for all the parts of the thing that you want to show in the UI. You will use these property names to access attributes of your object in QML later.

  1. class ThingWrapper(QtCore.QObject):
  2.     def __init__(self, thing):
  3.         QtCore.QObject.__init__(self)
  4.         self._thing = thing
  5.  
  6.     def _name(self):
  7.         return str(self._thing)
  8.  
  9.     changed = QtCore.Signal()
  10.  
  11.     name = QtCore.Property(unicode, _name, notify=changed)

Define your list model for your objects

You can subclass QAbstractListModel and implement the required methods to provide a proper data model to QML’s ListView. Theoretically, you could have multiple columns, but for simplicity, we just use one here, and then access the different attributes of our objects (one object per “row”). The list model here gets a list of (wrapped) “things” as constructor parameter. You could also generate objects on the fly if you want, just make sure that you return the proper value in the rowCount function.

  1. class ThingListModel(QtCore.QAbstractListModel):
  2.     COLUMNS = ('thing',)
  3.  
  4.     def __init__(self, things):
  5.         QtCore.QAbstractListModel.__init__(self)
  6.         self._things = things
  7.         self.setRoleNames(dict(enumerate(ThingListModel.COLUMNS)))
  8.  
  9.     def rowCount(self, parent=QtCore.QModelIndex()):
  10.         return len(self._things)
  11.  
  12.     def data(self, index, role):
  13.         if index.isValid() and role == ThingListModel.COLUMNS.index('thing'):
  14.             return self._things[index.row()]
  15.         return None

Create a controller for receiving events

For receiving events from QML, there are several possiblities. We simply create another QObject subclass and give it a Slot with one parameter (the wrapper object in the selected row). We pass the wrapper object from QML, and arrive at this point in the “Python world” and can do whatever we want with the object the user has selected.

  1. class Controller(QtCore.QObject):
  2.     @QtCore.Slot(QtCore.QObject)
  3.     def thingSelected(self, wrapper):
  4.         print 'User clicked on:', wrapper._thing.name
  5.         if wrapper._thing.number > 10:
  6.             print 'The number is greater than ten!'

Set up the QDeclarativeView

Here follows some generic boilerplate code for setting up the basic QApplication, QMainWindow and QDeclarativeView object tree to display QML. If you don’t want to use OpenGL acceleration, remove the lines glw = QtOpenGL.QGLWidget() and view.setViewport(glw).

  1. app = QtGui.QApplication(sys.argv)
  2.  
  3.  
  4. view = QtDeclarative.QDeclarativeView()
  5. view.setViewport(glw)
  6. view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

Your custom Python object

In an existing project, you would simply import your data model module and be done with it. Here, we create a dummy Person object (note that it is a pure Python object and does not know anything about QObject or PySide!) and some example data:

  1. class Person(object):
  2.     def __init__(self, name, number):
  3.         self.name = name
  4.         self.number = number
  5.  
  6.     def __str__(self):
  7.         return 'Person "%s" (%d)' % (self.name, self.number)
  8.  
  9. people = [
  10.         Person('Locke', 4),
  11.         Person('Reyes', 8),
  12.         Person('Ford', 15),
  13.         Person('Jarrah', 16),
  14.         Person('Shephard', 23),
  15.         Person('Kwon', 42),
  16. ]

Wrap your custom objects in QObjects

As we have defined our ThingWrapper class above, this is pretty straightforward using Python’s list comprehensions:

  1. things = [ThingWrapper(thing) for thing in people]

Connect the controller, the model and load the QML file

Again, this is easy, as we have already written most of the code and just need to glue all the parts together. Using setContextProperty we can expose QObject instances to the QML engine and access them using the name given as first parameter:

  1. controller = Controller()
  2. thingList = ThingListModel(things)
  3.  
  4. rc = view.rootContext()
  5.  
  6. rc.setContextProperty('controller', controller)
  7. rc.setContextProperty('pythonListModel', thingList)
  8.  
  9. view.setSource('PythonList.qml')

Show the window and start the application

Add the view to the window, show the window and finally start the application:

  1. m.setCentralWidget(view)
  2.  
  3. m.show()
  4.  
  5. app.exec_()

PythonList.qml

QML is pretty compact, and we only need to define the look of one row, and QML will take care of rendering every row separately. The important parts here are:

  • model references the list model, the pythonListModel corresponds to the model set using setContextProperty in Python
  • A nifty way to have alternating background colors: color: ((index % 2 == 0) ? “#222” : “#111”)
  • The text attribute of the Text item is taken from model.thing.name where model is our model, thing is the column of our model, and name is the property of our wrapper
  • When the item is clicked (MouseArea), the controller (from setContextProperty) gets its thingSelected slot called with model.thing as the first and only parameter

  1. import Qt 4.7
  2.  
  3. ListView {
  4.     id: pythonList
  5.     width: 400
  6.     height: 200
  7.  
  8.     model: pythonListModel
  9.  
  10.     delegate: Component {
  11.         Rectangle {
  12.             width: pythonList.width
  13.             height: 40
  14.             color: ((index % 2 == 0)?"#222":"#111")
  15.             Text {
  16.                 id: title
  17.                 elide: Text.ElideRight
  18.                 text: model.thing.name
  19.                 color: "white"
  20.                 font.bold: true
  21.                 anchors.leftMargin: 10
  22.                 anchors.fill: parent
  23.                 verticalAlignment: Text.AlignVCenter
  24.             }
  25.             MouseArea {
  26.                 anchors.fill: parent
  27.                 onClicked: { controller.thingSelected(model.thing) }
  28.             }
  29.         }
  30.     }
  31. }

Starting the example

This is how it looks when you run the example using python PythonList.py:

Screenshot: Python QML list

Categories:

  • Tutorial
  • LanguageBindings
  • snippets
  •