return python dict to QML (PySide2)

时间:2018-10-02 09:10:59

标签: python qml pyside2

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

main.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_())

main.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"]
 }
} 

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

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?

Thanks in advance :)

1 个答案:

答案 0 :(得分:1)

由于受支持,因此将python的基本类型导出到QML时会转换为相应的类型,但是要使Slot()返回某项,必须通过result参数来指示数据类型,在此QVariant中作为字符串。

示例:

main.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_())

main.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