Multi-selection-lists-in-Python-with-QML: Difference between revisions
No edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
[[Category:LanguageBindings::PySide]] | [[Category:LanguageBindings::PySide]] | ||
[[Category:snippets]] | |||
[[Category:Developing_with_Qt::Qt Quick]] | |||
[[Category:Developing_with_Qt::Qt Quick::QML]] | |||
[[Category:Developing_with_Qt::Qt Quick::Tutorial]] | |||
[toc align_right="yes" depth="2"] | |||
= Multi-selection lists in Python with QML = | = Multi-selection lists in Python with QML = | ||
Line 13: | Line 18: | ||
We can use the docstring as window title later on (using '''''doc'''''): | We can use the docstring as window title later on (using '''''doc'''''): | ||
<code> | <code> | ||
# -*- coding: utf-8 -*- | |||
"""Click-your-Zen of PySide""" | |||
</code> | |||
=== Imports === | === Imports === | ||
Line 21: | Line 28: | ||
We need '''sys''' for the command line arguments and we need '''this''' for some free sample data: | We need '''sys''' for the command line arguments and we need '''this''' for some free sample data: | ||
<code> | <code> | ||
import sys | |||
import this | |||
from PySide import QtCore | from PySide import QtCore | ||
from PySide import QtGui | |||
from PySide import QtDeclarative | |||
</code> | |||
=== QObject wrapper with | === 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 | 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!). | ||
<code> | <code> | ||
class ZenWrapper(QtCore.QObject): | |||
def ''init''(self, zenItem): | |||
QtCore.QObject.''init''(self) | |||
self._zenItem = zenItem | |||
self._checked = False | |||
def _name(self): | def _name(self): | ||
return self._zenItem | |||
def is_checked(self): | def is_checked(self): | ||
return self._checked | |||
def toggle_checked(self): | def toggle_checked(self): | ||
self._checked = not self._checked | |||
self.changed.emit() | |||
changed = QtCore.Signal() | changed = QtCore.Signal() | ||
name = QtCore.Property(unicode, ''name, notify=changed) | name = QtCore.Property(unicode, ''name, notify=changed) | ||
checked = QtCore.Property(bool, is_checked, notify=changed) | |||
</code> | |||
< | |||
h3. 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: | |||
def data(self, index, role): | <code> | ||
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()] | |||
</code> | |||
h3. 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: | |||
<code> | |||
class Controller(QtCore.QObject): | |||
&#64;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))) | |||
</code> | |||
=== Model and controller setup === | === Model and controller setup === | ||
Line 57: | Line 106: | ||
Here we generate some example data and instantiate the controller and the list model: | Here we generate some example data and instantiate the controller and the list model: | ||
<code> | <code> | ||
zenItems = [ZenWrapper(zenItem) for zenItem in ''.join([this.d.get(c, c) for c in this.s]).splitlines()[2:]] | |||
controller = Controller() | controller = Controller() | ||
zenItemList = ZenListModel(zenItems) | |||
</code> | |||
=== QApplication / QDeclarativeView + Glue code === | === QApplication / QDeclarativeView + Glue code === | ||
Line 65: | Line 117: | ||
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: | 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: | ||
<code> | <code> | ||
app = QtGui.QApplication(sys.argv) | |||
view = QtDeclarative.QDeclarativeView() | view = QtDeclarative.QDeclarativeView() | ||
view.setWindowTitle(''doc'') | |||
view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView) | |||
rc = view.rootContext() | rc = view.rootContext() | ||
rc.setContextProperty('controller', controller) | rc.setContextProperty('controller', controller) | ||
rc.setContextProperty('pythonListModel', zenItemList) | |||
view.setSource(''file''.replace('.py', '.qml')) | |||
view.show() | view.show() | ||
app.exec_() | |||
</code> | |||
== MultiList.qml == | == MultiList.qml == | ||
<code> | <code> | ||
import Qt 4.7 | |||
ListView { | ListView { | ||
id: pythonList | |||
width: 300 | |||
height: 500 | |||
model: pythonListModel | |||
delegate: Component { | 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) } | |||
} | |||
} | |||
} | |||
} | |||
</code> | |||
== How the example app looks == | == How the example app looks == | ||
Starting the app using '''python MultiList.py''' should give something like this: | Starting the app using '''python MultiList.py''' should give something like this: |
Revision as of 09:43, 25 February 2015
[toc align_right="yes" depth="2"]
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.
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)
h3. 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()]
h3. 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):
&#64;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: