return python dict to QML (PySide2)

前端 未结 1 1522
时光说笑
时光说笑 2021-01-15 18:56

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         


        
相关标签:
1条回答
  • 2021-01-15 19:12

    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.

    Example:

    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)
            }
        }
    }
    

    Output:

    qml: a :  1
    qml: b :  2
    
    0 讨论(0)
提交回复
热议问题