[PySide] List model from PySide to QML
-
Using a ListModel with a Repeater is rather straightforward. However, I'm struggling to produce a working model from PySide. My current test code is below. Any suggestions?
main.py
@#!/usr/bin/env python-- coding: utf-8 --
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtDeclarative import QDeclarativeViewclass TestModel(QAbstractListModel):
def init(self, items):
super(TestModel, self).init()
self.items = itemsdef rowCount(self, parent=QModelIndex()): return len(self.items) def data(self, index, role=Qt.DisplayRole): if role == Qt.DisplayRole: return QVariant(self.items[index.row()]) elif role == Qt.EditRole: return QVariant(self.items[index.row()]) else: return QVariant()
QObject and object yield the same result
#class TestObject(object):
class TestObject(QObject):
def init(self, message):
super(TestObject, self).init()
self.message = messageclass MainWindow(QDeclarativeView):
def init(self, parent=None):
super(MainWindow, self).init(parent)self.context = self.rootContext() # Both cause "ReferenceError: Can't find variable: message" self.context.setContextProperty("pyModel", test_model) #self.context.setContextProperty("pyModel", abstract_model) self.setWindowTitle("Test Bindigs") self.setSource(QUrl.fromLocalFile("main.qml"))
if name == 'main':
app = QApplication(sys.argv)# Create test objects test_one = TestObject("One") test_two = TestObject("Two") # Create test model test_model = [test_one, test_two] print("{}, {}".format(test_model[0].message, test_model[1].message)) # Create abstract test model abstract_model = TestModel([test_one, test_two]) # Setup main window window = MainWindow() window.show() sys.exit(app.exec_())@
main.qml
@import QtQuick 1.1FocusScope {
id: window
width: 400
height: 400
anchors.fill: parent
focus: true// Model ListModel { id: qmlModel ListElement { message: "First" } ListElement { message: "Second" } } // Delegate Component { id: testDelegate Rectangle { width: 100 height: 20 border.width: 1 Text { anchors.centerIn: parent text: message // ReferenceError: Can't find variable: message } } } // View Column { anchors.centerIn: parent Repeater { model: pyModel // Causes ReferenceError //model: qmlModel delegate: testDelegate } }
}@