访问作为信号发送到QML的Python字典条目

访问作为信号发送到QML的Python字典条目,python,qt,qml,pyside2,Python,Qt,Qml,Pyside2,首先,我知道有人提出了类似的问题。然而,我尝试过这个解决方案,但没有成功。下面是我的代码的一个最小可验证示例: from PySide2.QtGui import QGuiApplication from PySide2.QtQml import QQmlApplicationEngine from PySide2.QtCore import QObject, Signal, Slot class Dictionary(QObject): def __init__(self):

首先,我知道有人提出了类似的问题。然而,我尝试过这个解决方案,但没有成功。下面是我的代码的一个最小可验证示例:

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QObject, Signal, Slot
 
 
class Dictionary(QObject):
    def __init__(self):
        QObject.__init__(self)
        self.dictionary = {1: "Word1", 2: "Word2"}

    sendDict = Signal(dict)
    
    @Slot(bool)
    def s_dict(self, arg1):
        self.sendDict.emit(self.dictionary)

if __name__ == "__main__":
    import sys
 
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    dictionary = Dictionary()
    engine.rootContext().setContextProperty("dictionary", dictionary)
    engine.load("main.qml")
 
    engine.quit.connect(app.quit)
    sys.exit(app.exec_()) 
下面是QML文件:

import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.2
 
ApplicationWindow {
    visible: true
    width: 640
    height: 240
    title: qsTr("Minimum Verifiable Example")
    color: "whitesmoke"
 
    GridLayout {
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.right
        anchors.margins: 9
 
        columns: 4
        rows: 4
        rowSpacing: 10
        columnSpacing: 10
 
        Button {
            height: 40
            Layout.fillWidth: true
            text: qsTr("Emit dictionary!")
 
            Layout.columnSpan: 2
 
            onClicked: {
                dictionary.s_dict(true)
            }
        }
    }

 
    Connections {
        target: dictionary
        function onSendDict(arg1) {console.log(arg1)}
    }
}
简单地说,我想用
console.log
打印这个字典的元素,但是我得到的是:
qml:QVariant(PySide::PyObjectWrapper,)
。我也尝试为它编制索引,但没有用(它返回未定义)


谢谢你的时间

> QML将自动将C++ QLIST和QVIELTANMAP映射到JavaScript数组和对象,但这类自动翻译对于Python数据结构来说是不可用的。您可能有两种选择:

  • 使用QVariantMap而不是Python字典。这应该成为QML端的常规Javascript对象

  • 使用JSON并将Python数据结构编码为字符串,将字符串传递给QML,然后在Javascript中使用JSON.parse对其进行解码