[PySide] Fwd: How do I return an object in Python and use it in QML?

Tom Li biergaizi2009 at gmail.com
Sat Mar 9 08:08:26 CET 2013

Well, I have no knowledge with JavaScript, or CSS. I just want to use
QML as a beautiful ListView.

I'm writing a Twitter client. I implemented TweetItem and TweetModel.
The issue is that there is a role in TweetItem called original. I want
it to point to the original tweet.

But I can not use it with "." operator in QML. I get an undefined value.
What is the right way to do it?


Here's my code.


import sys
from PySide import QtCore, QtGui, QtDeclarative

class TweetModel(QtCore.QAbstractListModel):
    def __init__(self, prototype, parent=None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self.tweets = []

    def appendRow(self, item):

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.tweets)

    def data(self, index, role):
        return self.tweets[index.row()].data(role)

class TweetItem(QtCore.QAbstractItemModel):
    def __init__(self, id=None, type=None, user=None, content=None,
time=None, original=None, parent=None):
        QtCore.QAbstractItemModel.__init__(self, parent)
        self.idRole = QtCore.Qt.UserRole + 1
        # More Roles
        self.originalRole = QtCore.Qt.UserRole + 6

        self.id = id
        self.original = original

    def roleNames(self):
        names = {}
        names[self.idRole] = "id"
        names[self.originalRole] = "original"
        return names

    def data(self, role):
        if role == self.idRole:
            return self.id
        elif role == self.originalRole:
            return self.original
            return QtCore.QVariant()

if __name__ = "__main__":
    model = TweetModel(TweetItem(), QtGui.qApp)
    item = TweetItem("0001", None, model)
    model.appendRow(TweetItem("0002", item, model))

    App = QtGui.QApplication(sys.argv)
    view = QtDeclarative.QDeclarativeView()
    view.rootContext().setContextProperty("mymodel", model)


import QtQuick 1.0

Rectangle {
  width: 360
  height: 360

  ListView {
         anchors.fill: parent
         model: mymodel
         // original.id == undefined
         delegate: Component { Text { text: id + " " + original.id } }

More information about the PySide mailing list