Multi-selection-lists-in-Python-with-QML

From Qt Wiki
Jump to navigation Jump to search



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.

MultiList.py

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

# -*- coding: utf-8 -*-

"""Click-your-Zen of PySide"""

Imports

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

import sys
import this

from PySide import QtCore
from PySide import QtGui
from PySide import QtDeclarative

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!).

class ZenWrapper(QtCore.QObject):
 def ''init''(self, zenItem):
 QtCore.QObject.''init''(self)
 self._zenItem = zenItem
 self._checked = False

def _name(self):
 return self._zenItem

def is_checked(self):
 return self._checked

def toggle_checked(self):
 self._checked = not self._checked
 self.changed.emit()

changed = QtCore.Signal()

name = QtCore.Property(unicode, ''name, notify=changed)
 checked = QtCore.Property(bool, is_checked, notify=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:

class ZenListModel(QtCore.QAbstractListModel):
 definit<span class="zenItems self,">:
 QtCore.QAbstractListModel.</span>init''_(self)
 self._zenItems = zenItems
 self.setRoleNames({0: 'zenItem'})

def rowCount(self, parent=QtCore.QModelIndex()):
 return len(self._zenItems)

def checked(self):
 return [x for x in self._zenItems if x.checked]

def data(self, index, role):
 if index.isValid() and role == 0:
 return self.''zenItems[index.row()]

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:

class Controller(QtCore.QObject):
 @QtCore.Slot(QtCore.QObject, QtCore.QObject)
 def toggled(self, model, wrapper):
 global view,doc''_
 wrapper.toggle_checked()
 new_list = model.checked()
 print '='*20, 'New List', '='*20
 print ''.join(x.name for x in new_list)
 view.setWindowTitle('%s (d)' (''doc'', len(new_list)))

Model and controller setup

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

zenItems = [ZenWrapper(zenItem) for zenItem in  ''.join([this.d.get(c, c) for c in  this.s]).splitlines()[2:]]

controller = Controller()
zenItemList = ZenListModel(zenItems)

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:

app = QtGui.QApplication(sys.argv)

view = QtDeclarative.QDeclarativeView()
view.setWindowTitle(''doc'')
view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

rc = view.rootContext()

rc.setContextProperty('controller', controller)
rc.setContextProperty('pythonListModel', zenItemList)
view.setSource(''file''.replace('.py', '.qml'))

view.show()
app.exec_()

MultiList.qml

import Qt 4.7

ListView {
 id: pythonList
 width: 300
 height: 500
 model: pythonListModel

delegate: Component {
 Rectangle {
 width: pythonList.width
 height: 30
 color: model.zenItem.checked?"#00B8F5":(index%2?"#eee":"#ddd")
 Text {
 elide: Text.ElideRight
 text: model.zenItem.name
 color: (model.zenItem.checked?"white":"black")
 anchors {
 verticalCenter: parent.verticalCenter
 left: parent.left
 right: (model.zenItem.checked?checkbox.left:parent.right)
 leftMargin: 5
 }
 }
 Text {
 id: checkbox
 text: "✔"
 font.pixelSize: parent.height
 font.bold: true
 visible: model.zenItem.checked
 color: "white"
 anchors {
 verticalCenter: parent.verticalCenter
 right: parent.right
 rightMargin: 5
 }
 }
 MouseArea {
 anchors.fill: parent
 onClicked: { controller.toggled(pythonListModel, model.zenItem) }
 }
 }
 }
}

How the example app looks

Starting the app using python MultiList.py should give something like this:

Screenshotmulti.jpg