将 python dict 返回到 QML (PySide2) [英] return python dict to QML (PySide2)

查看:92
本文介绍了将 python dict 返回到 QML (PySide2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to find a way to return a python dictionary from a PySide2.QtCore.Slot.

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?

I think it is somehow done in QAbstractItemModel.roleNames() as it returns a QHash<int, QByteArray>?

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

If it doesn't work like this, can anyone please support me with "the correct way" of exchanging inforamtion between the python backend and the QML frontend?

提前致谢:)

推荐答案

python 的基本类型在导出到 QML 时被转换为对应的类型,因为它们是支持的,但是对于一个 Slot() 返回数据类型必须通过 result 参数指示,在这个 QVariant 中作为字符串.

The basic types of python when they are exported to QML are converted to their corresponding type since they are supported, but for a Slot() to return something the data type must be indicated through the result parameter, in this QVariant as a string.

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 dict 返回到 QML (PySide2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆