Question

I'm following this PySide tutorial as close as possible using PyQt5. When I run my code, I get this error: ReferenceError: pythonListModel is not defined, and the list shows up black with no items.

This is my code

def main():
    platform = Platform("Windows")
    platform_wrp = qml_platforms.PlatformsWrapper(platform)
    platform_model = qml_platforms.PlatformsListModel([platform_wrp])
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine(QUrl("main.qml"))
    context = engine.rootContext()
    context.setContextProperty('pythonListModel', platform_model)
    window = engine.rootObjects()[0]
    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

my model and wrapper

class PlatformsWrapper(QObject):
    def __init__(self, platform):
        QObject.__init__(self)
        self.platform = platform
    def full_name(self):
        return str(self.platform.full_name)
    changed = pyqtSignal()
    full_name = pyqtProperty("QString", _full_name, notify=changed)

class PlatformsListModel(QAbstractListModel):
     def __init__(self, platforms):
        QAbstractListModel.__init__(self)
        self.platforms = platforms
     def rowCount(self, parent=QModelIndex()):
         return len(self.platforms)
     def data(self, index):
         if index.isValid():
             return self.platforms[index.row()]
         return None

and my QML

import QtQuick 2.1
import QtQuick.Controls 1.1

ApplicationWindow{
ListView {
    id: pythonList
    width: 400
    height: 200

    model: pythonListModel

    delegate: Component {
        Rectangle {
            width: pythonList.width
            height: 40
            color: ((index % 2 == 0)?"#222":"#111")
            Text {
                id: title
                elide: Text.ElideRight
                text: model.platform.full_name
                color: "white"
                font.bold: true
                anchors.leftMargin: 10
                anchors.fill: parent
                verticalAlignment: Text.AlignVCenter
            }
            MouseArea {
                anchors.fill: parent
            }
        }
    }
}
}

Why can't Qt find my contextProperty?

Was it helpful?

Solution

The problem is that "main.qml" is loaded before you set context property. Try load file after you setup your context:

def main():
    platform = Platform("Windows")
    platform_wrp = qml_platforms.PlatformsWrapper(platform)
    platform_model = qml_platforms.PlatformsListModel([platform_wrp])
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    context = engine.rootContext()
    context.setContextProperty('pythonListModel', platform_model)
    engine.load( QUrl("main.qml") ) #load after context setup
    window = engine.rootObjects()[0]
    window.show()
    sys.exit(app.exec_())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top