Multi-selection-lists-in-Python-with-QML: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
=Multi-selection lists in Python with <span class="caps">QML</span>=
[[Category:LanguageBindings::PySide]]<br />[[Category:snippets]]<br />[[Category:Developing_with_Qt::Qt Quick]]<br />[[Category:Developing_with_Qt::Qt Quick::QML]]<br />[[Category:Developing_with_Qt::Qt Quick::Tutorial]]<br />[toc align_right=&quot;yes&amp;quot; depth=&quot;2&amp;quot;]


This is an extension of the [[Selectable-list-of-Python-objects-in-QML|Selectable list of Python objects in <span class="caps">QML</span>]] and focuses more on modifying the list and getting selected items out of the <span class="caps">QML</span> view.
= Multi-selection lists in Python with QML =


==MultiList.py==
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.
This is the Python code that takes care of setting up the model and controlling it.


===Encoding declaration and module docstring===
=== Encoding declaration and module docstring ===


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


===Imports===
<code><br /># <s>*</s> coding: utf-8 <s>*</s>
 
&quot;&quot;&quot;Click-your-Zen of PySide&amp;quot;&quot;&quot;<br /></code>
 
=== Imports ===


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:


===QObject wrapper with “checked” property===
<code><br />import sys<br />import this


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 <span class="caps">QML</span> would not know that something has changed!).
from PySide import QtCore<br />from PySide import QtGui<br />from PySide import QtDeclarative<br /></code>


===List model, with helper to get checked items===
=== QObject wrapper with &quot;checked&amp;quot; property ===


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:
Just as with the previous example, we now define a wrapper object. The difference here is that it has a &quot;checked&amp;quot; property and a convenience method for toggling the property (don't forget that you need to '''emit''' the &quot;changed&amp;quot; signal, otherwise QML would not know that something has changed!).


===Controller for toggling and retrieving changes===
<code><br />class ZenWrapper(QtCore.QObject):<br /> def ''init''(self, zenItem):<br /> QtCore.QObject.''init''(self)<br /> self._zenItem = zenItem<br /> self._checked = False


This controller provides a '''toggled''' slot that will be called by <span class="caps">QML</span> 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:
def _name(self):<br /> return self._zenItem


===Model and controller setup===
def is_checked(self):<br /> return self._checked
 
def toggle_checked(self):<br /> self._checked = not self._checked<br /> self.changed.emit()
 
changed = QtCore.Signal()
 
name = QtCore.Property(unicode, ''name, notify=changed)<br /> checked = QtCore.Property(bool, is_checked, notify=changed)<br /></code>
<br />h3. List model, with helper to get checked items
<br />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:
<br /><code><br />class ZenListModel(QtCore.QAbstractListModel):<br /> definit<span class="zenItems self,">:<br /> QtCore.QAbstractListModel.</span>init''_(self)<br /> self._zenItems = zenItems<br /> self.setRoleNames({0: 'zenItem'})
 
def rowCount(self, parent=QtCore.QModelIndex()):<br /> return len(self._zenItems)
 
def checked(self):<br /> return [x for x in self._zenItems if x.checked]
 
def data(self, index, role):<br /> if index.isValid() and role == 0:<br /> return self.''zenItems[index.row()]<br /></code>
<br />h3. Controller for toggling and retrieving changes
<br />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:
<br /><code><br />class Controller(QtCore.QObject):<br /> &amp;#64;QtCore.Slot(QtCore.QObject, QtCore.QObject)<br /> def toggled(self, model, wrapper):<br /> global view,doc''_<br /> wrapper.toggle_checked()<br /> new_list = model.checked()<br /> print '='*20, 'New List', '='*20<br /> print ''.join(x.name for x in new_list)<br /> view.setWindowTitle('%s (d)' (''doc'', len(new_list)))<br /></code>
 
=== Model and controller setup ===


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:


===QApplication / QDeclarativeView + Glue code===
<code><br />zenItems = [ZenWrapper(zenItem) for zenItem in  ''.join([this.d.get(c, c) for c in  this.s]).splitlines()[2:]]
 
controller = Controller()<br />zenItemList = ZenListModel(zenItems)<br /></code>
 
=== 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:
 
<code><br />app = QtGui.QApplication(sys.argv)
 
view = QtDeclarative.QDeclarativeView()<br />view.setWindowTitle(''doc'')<br />view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)


This piece of code creates a new QApplication instance, a new QDeclarativeView and also exposes the controller and the list model to the <span class="caps">QML</span> environment, so it can be accessed from there:
rc = view.rootContext()


==MultiList.qml==
rc.setContextProperty('controller', controller)<br />rc.setContextProperty('pythonListModel', zenItemList)<br />view.setSource(''file''.replace('.py', '.qml'))


==How the example app looks==
view.show()<br />app.exec_()<br /></code>


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


[[Image:5224693821_8edfbfda3d.jpg|Screenshot of example multi-selection list]]
<code><br />import Qt 4.7


===Categories:===
ListView {<br /> id: pythonList<br /> width: 300<br /> height: 500<br /> model: pythonListModel


* [[:Category:Developing with Qt|Developing_with_Qt]]
delegate: Component {<br /> Rectangle {<br /> width: pythonList.width<br /> height: 30<br /> color: model.zenItem.checked?&quot;#00B8F5&amp;quot;:(index%2?&quot;#eee&amp;quot;:&quot;#ddd&amp;quot;)<br /> Text {<br /> elide: Text.ElideRight<br /> text: model.zenItem.name<br /> color: (model.zenItem.checked?&quot;white&amp;quot;:&quot;black&amp;quot;)<br /> anchors {<br /> verticalCenter: parent.verticalCenter<br /> left: parent.left<br /> right: (model.zenItem.checked?checkbox.left:parent.right)<br /> leftMargin: 5<br /> }<br /> }<br /> Text {<br /> id: checkbox<br /> text: &quot;✔&amp;quot;<br /> font.pixelSize: parent.height<br /> font.bold: true<br /> visible: model.zenItem.checked<br /> color: &quot;white&amp;quot;<br /> anchors {<br /> verticalCenter: parent.verticalCenter<br /> right: parent.right<br /> rightMargin: 5<br /> }<br /> }<br /> MouseArea {<br /> anchors.fill: parent<br /> onClicked: { controller.toggled(pythonListModel, model.zenItem) }<br /> }<br /> }<br /> }<br />}<br /></code>
** [[:Category:Developing with Qt::Qt-Quick|Qt Quick]]
* [[:Category:Developing with Qt::Qt-Quick::QML|QML]]


* [[:Category:Developing with Qt::Qt-Quick::Tutorial|Tutorial]]
== How the example app looks ==


* [[:Category:LanguageBindings|LanguageBindings]]
Starting the app using '''python MultiList.py''' should give something like this:
** [[:Category:LanguageBindings::PySide|PySide]]
* [[:Category:snippets|snippets]]

Revision as of 09:21, 24 February 2015






[toc align_right="yes&quot; depth="2&quot;]

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

<br /># <s>*</s> coding: utf-8 <s>*</s>

&quot;&quot;&quot;Click-your-Zen of PySide&amp;quot;&quot;&quot;<br />

Imports

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

<br />import sys<br />import this

from PySide import QtCore<br />from PySide import QtGui<br />from PySide import QtDeclarative<br />

QObject wrapper with "checked&quot; property

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

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

def _name(self):<br /> return self._zenItem

def is_checked(self):<br /> return self._checked

def toggle_checked(self):<br /> self._checked = not self._checked<br /> self.changed.emit()

changed = QtCore.Signal()

name = QtCore.Property(unicode, ''name, notify=changed)<br /> checked = QtCore.Property(bool, is_checked, notify=changed)<br />


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:


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

def rowCount(self, parent=QtCore.QModelIndex()):<br /> return len(self._zenItems)

def checked(self):<br /> return [x for x in self._zenItems if x.checked]

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


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:


<br />class Controller(QtCore.QObject):<br /> &amp;#64;QtCore.Slot(QtCore.QObject, QtCore.QObject)<br /> def toggled(self, model, wrapper):<br /> global view,doc''_<br /> wrapper.toggle_checked()<br /> new_list = model.checked()<br /> print '='*20, 'New List', '='*20<br /> print ''.join(x.name for x in new_list)<br /> view.setWindowTitle('%s (d)' (''doc'', len(new_list)))<br />

Model and controller setup

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

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

controller = Controller()<br />zenItemList = ZenListModel(zenItems)<br />

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:

<br />app = QtGui.QApplication(sys.argv)

view = QtDeclarative.QDeclarativeView()<br />view.setWindowTitle(''doc'')<br />view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)

rc = view.rootContext()

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

view.show()<br />app.exec_()<br />

MultiList.qml

<br />import Qt 4.7

ListView {<br /> id: pythonList<br /> width: 300<br /> height: 500<br /> model: pythonListModel

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

How the example app looks

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