gpt4 book ai didi

python - 无法将 QAbstractListModel 传递给 QML

转载 作者:太空宇宙 更新时间:2023-11-04 01:18:22 24 4
gpt4 key购买 nike

我正在关注 this PySide tutorial尽可能接近使用 PyQt5。当我运行我的代码时,出现此错误: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?

最佳答案

问题是“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_())

关于python - 无法将 QAbstractListModel 传递给 QML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22888520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com