gpt4 book ai didi

python - 将 python 字典返回到 QML (PySide2)

转载 作者:行者123 更新时间:2023-12-01 01:33:22 30 4
gpt4 key购买 nike

我正在尝试找到一种从 PySide2.QtCore.Slot 返回 python 字典的方法。

ma​​in.py

import sys
from PySide2.QtCore import QObject, Slot
from PySide2.QtGui import QGuiApplication, QQmlApplicationEngine

class Backend(QObject):
def __init__(self, parent=None):
return super().__init(parent)

@Slot(result=QObject)
def get_data(self):
data = {}
data["info1"] = "some information"
data["info2"] = "some more information"
data["info3"] = 42
return data

if __name__ == '__main':
BACKEND = Backend()
APP = QGuiApplication(sys.argv)
ENGINE = QQmlApplicationEngine(APP)
ENGINE.rootContext().setContextProperty('backend', BACKEND)
ENGINE.load("main.qml")
sys.exit(APP.exec_())

ma​​in.qml:

import QtQuick 2.4
import QtQuick.Controls 1.4

ApplicationWindow {
id: root
width: 640
height: 480
visible: true
color: "#F0F0F0"
title: qsTr("Test")

Text {
anchors.centerIn: parent
text: backend.get_data()["info1"]
}
}

我认为它是在 QAbstractItemModel.roleNames() 中以某种方式完成的,因为它返回 QHash<int, QByteArray>

如果它不能像这样工作,任何人都可以支持我在 python 后端和 QML 前端之间交换信息的“正确方法”吗?

提前致谢:)

最佳答案

Python 的基本类型在导出到 QML 时会转换为相应的类型,因为它们受支持,但要让 Slot() 返回某些内容,必须通过 result 参数,在此 QVariant 中作为字符串。

示例:

ma​​in.py

from PySide2 import QtCore, QtGui, QtQml


class Helper(QtCore.QObject):
@QtCore.Slot(result='QVariant')
def foo(self):
return {"a": 1, "b": 2}


if __name__ == '__main__':
import sys

app = QtGui.QGuiApplication(sys.argv)

engine = QtQml.QQmlApplicationEngine()
helper = Helper()
engine.rootContext().setContextProperty("helper", helper)
engine.load(QtCore.QUrl.fromLocalFile('main.qml'))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())

ma​​in.qml

import QtQuick 2.9
import QtQuick.Controls 2.4

ApplicationWindow {
visible: true
Component.onCompleted: {
var data = helper.foo()
for(var key in data){
var value = data[key]
console.log(key, ": ", value)
}
}
}

输出:

qml: a :  1
qml: b : 2

关于python - 将 python 字典返回到 QML (PySide2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52605338/

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