3

我正在使用 PyQt5 尽可能接近这个 PySide 教程。当我运行我的代码时,我收到了这个错误:ReferenceError: pythonListModel is not defined,并且列表显示为黑色,没有项目。

这是我的代码

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()

我的模型和包装

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

和我的 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
            }
        }
    }
}
}

为什么 Qt 找不到我的 contextProperty?

4

1 回答 1

4

问题是在设置上下文属性之前加载了“main.qml”。设置上下文后尝试加载文件:

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_())
于 2014-04-06T00:40:24.973 回答