On Saturday 20 November 2010 14:30:19 Thomas Perl wrote:
> Hi!

Hi, I did a example to show, test and learn how to export a QAbstractItemModel 
do QML, including user defined roles and... it works! :-D

The example is attached, I'll upload it to git soon.
 
> I'm trying to display a list of arbitrary Python objects inside a QML
> ListView where I can leave the representation of each Python object to
> the delegate. Ideally (ignoring all wrapping in QObjects with slots,
> properties, etc..), I'd like to do something along those lines:
> 
> class Person:
>     def __init__(self, id, name):
>         self.id = id
>         self.name = name
> 
> # Imagine this is properly wrapped as slot in a QObject
> def person_selected(p):
>     print 'user clicked on person:', p.name, 'with id:', p.id
> 
> persons = [
>     Person(1, 'AA'),
>     Person(2, 'BB'),
>     Person(3, 'CC')
> ]
> 
> # ... create QDeclarativeView ...
> # ... get root context as "ctx" ...
> 
> ctx.setContextProperty('persons', persons)
> ctx.setContextProperty('person_selected', person_selected)
> 
> In my QML file, I then want to set "persons" as the model for my
> ListView, and set up the mouse handler in the delegate to call
> person_selected() with the person that has been clicked. In the
> delegate, I want to access the attributes of Person (e.g. p.name), and
> (thinking about future uses), I might also use methods of it (e.g.
> p.formatBirthday()) as well, not just attributes.
> 
> In the pyside-examples repository, I've only found a simple example
> that deals with a list of strings (in
> examples/declarative/scrolling.py), which works and is nice, but does
> not really map to my real-world use case where I want to display a
> list of items that have different properties and where I also want to
> retrieve the original item in a "item selected" callback.
> 
> Trying to come up with something as described above does not give me
> any results. I have tried playing around with QAbstractListModel as
> alternative already, which resulted in
> http://bugs.openbossa.org/show_bug.cgi?id=477.
> 
> Any pointers and suggestions on how to best create such a selection
> list of Python objects is greatly appreciated!
> 
> Thanks!
> Thomas
> _______________________________________________
> PySide mailing list
> [email protected]
> http://lists.openbossa.org/listinfo/pyside

-- 
Hugo Parente Lima
INdT - Instituto Nokia de Tecnologia

-- 
Hugo Parente Lima
INdT - Instituto Nokia de Tecnologia
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
**     the names of its contributors may be used to endorse or promote
**     products derived from this software without specific prior written
**     permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/

import Qt 4.7

ListView {
    width: 100
    height: 100
    anchors.fill: parent
    model: myModel
    delegate: Component {
        Rectangle {
            height: 25
            width: 100
            Text { text: modelData }
        }
    }
}
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtDeclarative import *

class PersonModel (QAbstractListModel):

    MyRole = Qt.UserRole + 1

    def __init__(self, parent = None):
        QAbstractListModel.__init__(self, parent)
        self.setRoleNames({
            PersonModel.MyRole : 'modelData',
            Qt.DisplayRole : 'display' # Qt asserts if you don't define a display role
            })
        self._data = []

    def rowCount(self, index):
        return len(self._data)

    def data(self, index, role):
        d = self._data[index.row()]

        if role == Qt.DisplayRole:
            return d['name']
        elif role == Qt.DecorationRole:
            return Qt.black
        elif role == PersonModel.MyRole:
            return d['myrole']
        return None

    def populate(self):
        self._data.append({'name':'Qt', 'myrole':'role1'})
        self._data.append({'name':'PySide', 'myrole':'role2'})

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = QDeclarativeView()

    myModel = PersonModel()
    myModel.populate()

    view.rootContext().setContextProperty("myModel", myModel)
    view.setSource('view.qml')
    view.show()

    app.exec_()


Attachment: signature.asc
Description: This is a digitally signed message part.

_______________________________________________
PySide mailing list
[email protected]
http://lists.openbossa.org/listinfo/pyside

Reply via email to