Selectable-list-of-Python-objects-in-QML: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
=Selectable list of Python objects in <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 [[PySide]] code example shows you how to display a list of arbitrary Python objects in [[QML|<span class="caps">QML</span>]] and to get the “real” Python object in a callback when the user clicks on a list item. This is done by wrapping the Python objects inside a QObject. Of course, if you are developing a new application, you can create your model entity objects directly as QObject subclasses, but for adding a <span class="caps">QML</span> UI on top of existing Python code, this should be very useful.
= Selectable list of Python objects in QML =
 
This [[PySide]] code example shows you how to display a list of arbitrary Python objects in [[QML]] and to get the &quot;real&amp;quot; Python object in a callback when the user clicks on a list item. This is done by wrapping the Python objects inside a QObject. Of course, if you are developing a new application, you can create your model entity objects directly as QObject subclasses, but for adding a QML UI on top of existing Python code, this should be very useful.


This example consists of two files:
This example consists of two files:


* '''PythonList.py''' Our Python code
* '''PythonList.py''' - Our Python code
* '''PythonList.qml''' The corresponding <span class="caps">QML</span> UI
* '''PythonList.qml''' - The corresponding QML UI


==PythonList.py==
== PythonList.py ==


This is the main module. After finishing writing it, you can start it using '''python PythonList.py'''
This is the main module. After finishing writing it, you can start it using '''python PythonList.py'''


===Import the required modules===
=== Import the required modules ===
 
This is pretty straightforward. If you don’t have OpenGL support on your target platform (or you don’t want to use OpenGL-accelerated <span class="caps">QML</span>), simply remove the line '''from PySide import QtOpenGL'''.
 
===Define a simple QObject wrapper===


Create a new QObject subclass that gets your custom Python object (called “thing” in this example) as constructor parameter. You can then define different properties (QtCore.Property) for all the parts of the thing that you want to show in the UI. You will use these property names to access attributes of your object in <span class="caps">QML</span> later.
This is pretty straightforward. If you don't have OpenGL support on your target platform (or you don't want to use OpenGL-accelerated QML), simply remove the line '''from PySide import QtOpenGL'''.


===Define your list model for your objects===
<code><br />import sys


You can subclass QAbstractListModel and implement the required methods to provide a proper data model to <span class="caps">QML</span>’s ListView. Theoretically, you could have multiple columns, but for simplicity, we just use one here, and then access the different attributes of our objects (one object per “row”). The list model here gets a list of (wrapped) “things” as constructor parameter. You could also generate objects on the fly if you want, just make sure that you return the proper value in the '''rowCount''' function.
from PySide import QtCore<br />from PySide import QtGui<br />from PySide import QtDeclarative<br />from PySide import QtOpenGL<br /></code>


===Create a controller for receiving events===
=== Define a simple QObject wrapper ===


For receiving events from <span class="caps">QML</span>, there are several possiblities. We simply create another QObject subclass and give it a Slot with one parameter (the wrapper object in the selected row). We pass the wrapper object from <span class="caps">QML</span>, and arrive at this point in the “Python world” and can do whatever we want with the object the user has selected.
Create a new QObject subclass that gets your custom Python object (called &quot;thing&amp;quot; in this example) as constructor parameter. You can then define different properties (QtCore.Property) for all the parts of the thing that you want to show in the UI. You will use these property names to access attributes of your object in QML later.


===Set up the QDeclarativeView===
<code><br />class ThingWrapper(QtCore.QObject):<br /> def ''init''(self, thing):<br /> QtCore.QObject.''init''(self)<br /> self._thing = thing


Here follows some generic boilerplate code for setting up the basic QApplication, QMainWindow and QDeclarativeView object tree to display <span class="caps">QML</span>. If you don’t want to use OpenGL acceleration, remove the lines '''glw = QtOpenGL.QGLWidget()''' and '''view.setViewport(glw)'''.
def _name(self):<br /> return str(self._thing)


===Your custom Python object===
changed = QtCore.Signal()


In an existing project, you would simply import your data model module and be done with it. Here, we create a dummy Person object (note that it is a pure Python object and does not know anything about QObject or PySide!) and some example data:
name = QtCore.Property(unicode, ''name, notify=changed)<br /></code>
<br />h3. Define your list model for your objects
<br />You can subclass QAbstractListModel and implement the required methods to provide a proper data model to QML's ListView. Theoretically, you could have multiple columns, but for simplicity, we just use one here, and then access the different attributes of our objects (one object per &quot;row&amp;quot;). The list model here gets a list of (wrapped) &quot;things&amp;quot; as constructor parameter. You could also generate objects on the fly if you want, just make sure that you return the proper value in the '''rowCount''' function.
<br /><code><br />class ThingListModel(QtCore.QAbstractListModel):<br /> COLUMNS = ('thing',)
<br /> definit<span class="things self,">:<br /> QtCore.QAbstractListModel.</span>init''_(self)<br /> self._things = things<br /> self.setRoleNames(dict(enumerate(ThingListModel.COLUMNS)))


===Wrap your custom objects in QObjects===
def rowCount(self, parent=QtCore.QModelIndex()):<br /> return len(self._things)


As we have defined our ThingWrapper class above, this is pretty straightforward using Python’s list comprehensions:
def data(self, index, role):<br /> if index.isValid() and role == ThingListModel.COLUMNS.index('thing'):<br /> return self._things[index.row()]<br /> return None<br /></code>


===Connect the controller, the model and load the <span class="caps">QML</span> file===
=== Create a controller for receiving events ===


Again, this is easy, as we have already written most of the code and just need to glue all the parts together. Using '''setContextProperty''' we can expose QObject instances to the <span class="caps">QML</span> engine and access them using the name given as first parameter:
For receiving events from QML, there are several possiblities. We simply create another QObject subclass and give it a Slot with one parameter (the wrapper object in the selected row). We pass the wrapper object from QML, and arrive at this point in the &quot;Python world&amp;quot; and can do whatever we want with the object the user has selected.


===Show the window and start the application===
<code><br />class Controller(QtCore.QObject):<br /> &amp;#64;QtCore.Slot(QtCore.QObject)<br /> def thingSelected(self, wrapper):<br /> print 'User clicked on:', wrapper._thing.name<br /> if wrapper.''thing.number &gt; 10:<br /> print 'The number is greater than ten!'<br /></code>
<br />h3. Set up the QDeclarativeView
<br />Here follows some generic boilerplate code for setting up the basic QApplication, QMainWindow and QDeclarativeView object tree to display QML. If you don't want to use OpenGL acceleration, remove the lines '''glw = QtOpenGL.QGLWidget()''' and '''view.setViewport(glw)'''.
<br /><code><br />app = QtGui.QApplication(sys.argv)
<br />m = QtGui.QMainWindow()
<br />view = QtDeclarative.QDeclarativeView()<br />glw = QtOpenGL.QGLWidget()<br />view.setViewport(glw)<br />view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)<br /></code>
<br />h3. Your custom Python object
<br />In an existing project, you would simply import your data model module and be done with it. Here, we create a dummy Person object (note that it is a pure Python object and does not know anything about QObject or PySide!) and some example data:
<br /><code><br />class Person(object):<br /> definit<span class="number name, self,">:<br /> self.name = name<br /> self.number = number
<br /> def</span>str<span class="self">:<br /> return 'Person &quot;%s&amp;quot; (d)' (self.name, self.number)
<br />people = [<br /> Person('Locke', 4),<br /> Person('Reyes', 8),<br /> Person('Ford', 15),<br /> Person('Jarrah', 16),<br /> Person('Shephard', 23),<br /> Person('Kwon', 42),<br />]<br /></code>
<br />h3. Wrap your custom objects in QObjects
<br />As we have defined our ThingWrapper class above, this is pretty straightforward using Python's list comprehensions:
<br /><code><br />things = [ThingWrapper(thing) for thing in people]<br /></code>
<br />h3. Connect the controller, the model and load the QML file
<br />Again, this is easy, as we have already written most of the code and just need to glue all the parts together. Using '''setContextProperty''' we can expose QObject instances to the QML engine and access them using the name given as first parameter:
<br /><code><br />controller = Controller()<br />thingList = ThingListModel(things)
<br />rc = view.rootContext()
<br />rc.setContextProperty('controller', controller)<br />rc.setContextProperty('pythonListModel', thingList)
<br />view.setSource('PythonList.qml')<br /></code>
<br />h3. Show the window and start the application
<br />Add the view to the window, show the window and finally start the application:
<br /><code><br />m.setCentralWidget(view)
<br />m.show()
<br />app.exec</span>''()<br /></code>


Add the view to the window, show the window and finally start the application:
== PythonList.qml ==


==PythonList.qml==
QML is pretty compact, and we only need to define the look of one row, and QML will take care of rendering every row separately. The important parts here are:
 
<span class="caps">QML</span> is pretty compact, and we only need to define the look of one row, and <span class="caps">QML</span> will take care of rendering every row separately. The important parts here are:


* '''model''' references the list model, the '''pythonListModel''' corresponds to the model set using '''setContextProperty''' in Python
* '''model''' references the list model, the '''pythonListModel''' corresponds to the model set using '''setContextProperty''' in Python
* A nifty way to have alternating background colors: '''color: ((index % 2 == 0) ? #222” : #111”)'''
* A nifty way to have alternating background colors: '''color: ((index % 2 == 0) ? &quot;#222&amp;quot; : &quot;#111&amp;quot;)'''
* The '''text''' attribute of the '''Text''' item is taken from '''model.thing.name''' where '''model''' is our model, '''thing''' is the column of our model, and '''name''' is the property of our wrapper
* The '''text''' attribute of the '''Text''' item is taken from '''model.thing.name''' where '''model''' is our model, '''thing''' is the column of our model, and '''name''' is the property of our wrapper
* When the item is clicked (MouseArea), the '''controller''' (from '''setContextProperty''') gets its '''thingSelected''' slot called with '''model.thing''' as the first and only parameter
* When the item is clicked (MouseArea), the '''controller''' (from '''setContextProperty''') gets its '''thingSelected''' slot called with '''model.thing''' as the first and only parameter


==Starting the example==
<code><br />import Qt 4.7


This is how it looks when you run the example using '''python PythonList.py''':
ListView {<br /> id: pythonList<br /> width: 400<br /> height: 200


[[Image:5224949144_ac18a8f36e_z.jpg|Screenshot: Python QML list]]
model: pythonListModel


===Categories:===
delegate: Component {<br /> Rectangle {<br /> width: pythonList.width<br /> height: 40<br /> color: ((index % 2 == 0)?&quot;#222&amp;quot;:&quot;#111&amp;quot;)<br /> Text {<br /> id: title<br /> elide: Text.ElideRight<br /> text: model.thing.name<br /> color: &quot;white&amp;quot;<br /> font.bold: true<br /> anchors.leftMargin: 10<br /> anchors.fill: parent<br /> verticalAlignment: Text.AlignVCenter<br /> }<br /> MouseArea {<br /> anchors.fill: parent<br /> onClicked: { controller.thingSelected(model.thing) }<br /> }<br /> }<br /> }<br />}<br /></code>


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


* [[:Category:Developing with Qt::Qt-Quick::Tutorial|Tutorial]]
This is how it looks when you run the example using '''python PythonList.py''':
 
* [[:Category:LanguageBindings|LanguageBindings]]
** [[:Category:LanguageBindings::PySide|PySide]]
* [[:Category:snippets|snippets]]

Revision as of 08:53, 24 February 2015






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

Selectable list of Python objects in QML

This PySide code example shows you how to display a list of arbitrary Python objects in QML and to get the "real&quot; Python object in a callback when the user clicks on a list item. This is done by wrapping the Python objects inside a QObject. Of course, if you are developing a new application, you can create your model entity objects directly as QObject subclasses, but for adding a QML UI on top of existing Python code, this should be very useful.

This example consists of two files:

  • PythonList.py - Our Python code
  • PythonList.qml - The corresponding QML UI

PythonList.py

This is the main module. After finishing writing it, you can start it using python PythonList.py

Import the required modules

This is pretty straightforward. If you don't have OpenGL support on your target platform (or you don't want to use OpenGL-accelerated QML), simply remove the line from PySide import QtOpenGL.

<br />import sys

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

Define a simple QObject wrapper

Create a new QObject subclass that gets your custom Python object (called "thing&quot; in this example) as constructor parameter. You can then define different properties (QtCore.Property) for all the parts of the thing that you want to show in the UI. You will use these property names to access attributes of your object in QML later.

<br />class ThingWrapper(QtCore.QObject):<br /> def ''init''(self, thing):<br /> QtCore.QObject.''init''(self)<br /> self._thing = thing

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

changed = QtCore.Signal()

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


h3. Define your list model for your objects
You can subclass QAbstractListModel and implement the required methods to provide a proper data model to QML's ListView. Theoretically, you could have multiple columns, but for simplicity, we just use one here, and then access the different attributes of our objects (one object per "row&quot;). The list model here gets a list of (wrapped) "things&quot; as constructor parameter. You could also generate objects on the fly if you want, just make sure that you return the proper value in the rowCount function.


<br />class ThingListModel(QtCore.QAbstractListModel):<br /> COLUMNS = ('thing',)
<br /> definit<span class="things self,">:<br /> QtCore.QAbstractListModel.</span>init''_(self)<br /> self._things = things<br /> self.setRoleNames(dict(enumerate(ThingListModel.COLUMNS)))

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

def data(self, index, role):<br /> if index.isValid() and role == ThingListModel.COLUMNS.index('thing'):<br /> return self._things[index.row()]<br /> return None<br />

Create a controller for receiving events

For receiving events from QML, there are several possiblities. We simply create another QObject subclass and give it a Slot with one parameter (the wrapper object in the selected row). We pass the wrapper object from QML, and arrive at this point in the "Python world&quot; and can do whatever we want with the object the user has selected.

<br />class Controller(QtCore.QObject):<br /> &amp;#64;QtCore.Slot(QtCore.QObject)<br /> def thingSelected(self, wrapper):<br /> print 'User clicked on:', wrapper._thing.name<br /> if wrapper.''thing.number &gt; 10:<br /> print 'The number is greater than ten!'<br />


h3. Set up the QDeclarativeView
Here follows some generic boilerplate code for setting up the basic QApplication, QMainWindow and QDeclarativeView object tree to display QML. If you don't want to use OpenGL acceleration, remove the lines glw = QtOpenGL.QGLWidget() and view.setViewport(glw).


<br />app = QtGui.QApplication(sys.argv)
<br />m = QtGui.QMainWindow()
<br />view = QtDeclarative.QDeclarativeView()<br />glw = QtOpenGL.QGLWidget()<br />view.setViewport(glw)<br />view.setResizeMode(QtDeclarative.QDeclarativeView.SizeRootObjectToView)<br />


h3. Your custom Python object
In an existing project, you would simply import your data model module and be done with it. Here, we create a dummy Person object (note that it is a pure Python object and does not know anything about QObject or PySide!) and some example data:


<br />class Person(object):<br /> definit<span class="number name, self,">:<br /> self.name = name<br /> self.number = number
<br /> def</span>str<span class="self">:<br /> return 'Person &quot;%s&amp;quot; (d)' (self.name, self.number)
<br />people = [<br /> Person('Locke', 4),<br /> Person('Reyes', 8),<br /> Person('Ford', 15),<br /> Person('Jarrah', 16),<br /> Person('Shephard', 23),<br /> Person('Kwon', 42),<br />]<br />


h3. Wrap your custom objects in QObjects
As we have defined our ThingWrapper class above, this is pretty straightforward using Python's list comprehensions:


<br />things = [ThingWrapper(thing) for thing in people]<br />


h3. Connect the controller, the model and load the QML file
Again, this is easy, as we have already written most of the code and just need to glue all the parts together. Using setContextProperty we can expose QObject instances to the QML engine and access them using the name given as first parameter:


<br />controller = Controller()<br />thingList = ThingListModel(things)
<br />rc = view.rootContext()
<br />rc.setContextProperty('controller', controller)<br />rc.setContextProperty('pythonListModel', thingList)
<br />view.setSource('PythonList.qml')<br />


h3. Show the window and start the application
Add the view to the window, show the window and finally start the application:


<br />m.setCentralWidget(view)
<br />m.show()
<br />app.exec</span>''()<br />

PythonList.qml

QML is pretty compact, and we only need to define the look of one row, and QML will take care of rendering every row separately. The important parts here are:

  • model references the list model, the pythonListModel corresponds to the model set using setContextProperty in Python
  • A nifty way to have alternating background colors: color: ((index % 2 == 0) ? "#222&quot; : "#111&quot;)
  • The text attribute of the Text item is taken from model.thing.name where model is our model, thing is the column of our model, and name is the property of our wrapper
  • When the item is clicked (MouseArea), the controller (from setContextProperty) gets its thingSelected slot called with model.thing as the first and only parameter
<br />import Qt 4.7

ListView {<br /> id: pythonList<br /> width: 400<br /> height: 200

model: pythonListModel

delegate: Component {<br /> Rectangle {<br /> width: pythonList.width<br /> height: 40<br /> color: ((index % 2 == 0)?&quot;#222&amp;quot;:&quot;#111&amp;quot;)<br /> Text {<br /> id: title<br /> elide: Text.ElideRight<br /> text: model.thing.name<br /> color: &quot;white&amp;quot;<br /> font.bold: true<br /> anchors.leftMargin: 10<br /> anchors.fill: parent<br /> verticalAlignment: Text.AlignVCenter<br /> }<br /> MouseArea {<br /> anchors.fill: parent<br /> onClicked: { controller.thingSelected(model.thing) }<br /> }<br /> }<br /> }<br />}<br />

Starting the example

This is how it looks when you run the example using python PythonList.py: