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

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

Multi-selection lists in Python with QML

This is an extension of the Selectable list of Python objects in QML and focuses more on modifying the list and getting selected items out of the QML view.

This is the Python code that takes care of setting up the model and controlling it.

Encoding declaration and module docstring

We can use the docstring as window title later on (using doc):


We need sys for the command line arguments and we need this for some free sample data:

QObject wrapper with “checked” property

Just as with the previous example, we now define a wrapper object. The difference here is that it has a “checked” property and a convenience method for toggling the property (don’t forget that you need to emit the “changed” signal, otherwise QML would not know that something has changed!).

List model, with helper to get checked items

This is again mostly the same as in the previous example, but we add a new helper method checked that takes care of retrieving all the checked items from the zenItems list:

Controller for toggling and retrieving changes

This controller provides a toggled slot that will be called by QML when we click on an item. We toggle the checked state of the item and (for the sake of demonstration) get the list of currently-checked items and print it on the console. We also set the window title to show the amount of currently selected items:

Model and controller setup

Here we generate some example data and instantiate the controller and the list model:

QApplication / QDeclarativeView + Glue code

This piece of code creates a new QApplication instance, a new QDeclarativeView and also exposes the controller and the list model to the QML environment, so it can be accessed from there:


How the example app looks

Starting the app using python should give something like this:

Screenshot of example multi-selection list