gpt4 book ai didi

python - 使用 PyQt 动态将项目设置为 QML ListModel

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:37 25 4
gpt4 key购买 nike

我有一个代表时间表的 QML,它从数据库获取值,因此我需要从我的 python 代码将值插入到 ListModel 中。 QML 看起来像这样:

function append(newElement) {
scheduleList.model.append(newElement)
}

ListView {
id: scheduleList
model: scheduleModel
delegate: scheduleItem

section.property: "day"
section.delegate: sectionDelegate
}

Component {
id: scheduleItem
Rectangle {
Row {
spacing: 15
Text {
text: lesson
}
Text {
text: subject
}
}
}
}

Component {
id: sectionDelegate
Rectangle {
id: root
Text {
id: label
text: section
}
}
}

我有一个函数,应该将值插入到 QML ListModel:

class ScheduleView(QObject):
def __init__(self, parent=None):
QObject.__init__(self, parent=parent)
self._presenter = SchedulePresenter(self)
self._widget = QQuickWidget(parent)
self._widget.rootContext().setContextProperty('scheduleView', self)
self._widget.rootContext().setContextProperty('groupsModel', self)
self._widget.setSource(QUrl('modules/schedule/Form.qml'))

def reprSchedules(self):
values = [{"lesson": "1", "subject": "PE", "day": "Monday"},
{"lesson": "2", "subject": "PE", "day": "Monday"},
{"lesson": "3", "subject": "PE", "day": "Monday"}]
#model = self._widget.rootObject().findChild(QObject, "scheduleModel")

我不知道该怎么做。请问你能帮帮我吗?我正在使用Python2.7、PyQt5.9、QtQuick2.5

最佳答案

对于此任务,您可以通过 QMetaObject.invokeMethod() 调用您在 .qml 中实现的追加函数,如下所示:

ma​​in.py

counter = 0

def onTimeout(obj):
global counter
value = {"lesson": str(counter), "subject": "PE", "day": QDate.longDayName(1 + counter % 7)}
QMetaObject.invokeMethod(obj, "append", Q_ARG(QVariant, value))
counter += 1


if __name__ == '__main__':
app = QApplication(sys.argv)
w = QQuickWidget()
w.setSource(QUrl('main.qml'))
timer = QTimer()
timer.timeout.connect(lambda: onTimeout(w.rootObject()))
timer.start(1000)
w.show()
sys.exit(app.exec_())

ma​​in.qml

import QtQuick 2.0

Rectangle {
width: 640
height: 480

function append(newElement) {
scheduleModel.append(newElement)
}
ListModel {
id: scheduleModel
}

ListView {
anchors.fill: parent
id: scheduleList
model: scheduleModel
delegate: scheduleItem

section.property: "day"
section.delegate: sectionDelegate
}


Component {
id: scheduleItem
Row {
spacing: 15
Text {
text: lesson
}
Text {
text: subject
}
}
}

Component {
id: sectionDelegate
Text {
id: label
text: section
}
}
}

完整的示例可以在下面的link中找到。

关于python - 使用 PyQt 动态将项目设置为 QML ListModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721954/

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