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

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
(Rename category "LanguageBindings::PySide" -> "PySide")
 
(8 intermediate revisions by 3 users not shown)
Line 1: Line 1:
=Multi-selection lists in Python with <span class="caps">QML</span>=


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.


==MultiList.py==
[[Category:PySide]]
[[Category:snippets]]
[[Category:Developing_with_Qt::Qt Quick]]
[[Category:Developing_with_Qt::Qt Quick::QML]]
[[Category:Developing_with_Qt::Qt Quick::Tutorial]]
 
 
 
 
This is an extension of the [[Selectable-list-of-Python-objects-in-QML|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>
# -*- coding: utf-8 -*-
 
"""Click-your-Zen of PySide"""
</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>
import sys
import this
 
from PySide import QtCore
from PySide import QtGui
from PySide import QtDeclarative
</code>
 
=== 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!).
 
<code>
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()


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!).
changed = QtCore.Signal()


===List model, with helper to get checked items===
name = QtCore.Property(unicode, ''name, notify=changed)
checked = QtCore.Property(bool, is_checked, notify=changed)
</code>


=== 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:
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===
<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]


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 data(self, index, role):
if index.isValid() and role == 0:
return self.''zenItems[index.row()]
</code>


===Model and controller setup===
=== 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):
@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 ===


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>
zenItems = [ZenWrapper(zenItem) for zenItem in  ''.join([this.d.get(c, c) for c in  this.s]).splitlines()[2:]]


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:
controller = Controller()
zenItemList = ZenListModel(zenItems)
</code>


==MultiList.qml==
=== QApplication / QDeclarativeView + Glue code ===


==How the example app looks==
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:


Starting the app using '''python MultiList.py''' should give something like this:
<code>
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_()
</code>
 
== MultiList.qml ==
 
<code>
import Qt 4.7


[[Image:5224693821_8edfbfda3d.jpg|Screenshot of example multi-selection list]]
ListView {
id: pythonList
width: 300
height: 500
model: pythonListModel


===Categories:===
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>


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


* [[:Category:Developing with Qt::Qt-Quick::Tutorial|Tutorial]]
Starting the app using '''python MultiList.py''' should give something like this:


* [[:Category:LanguageBindings|LanguageBindings]]
[[Image:Screenshotmulti.jpg]]
** [[:Category:LanguageBindings::PySide|PySide]]
* [[:Category:snippets|snippets]]

Latest revision as of 03:30, 5 June 2016



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