我如何用信号将python字典发送到QML接口?

2024-09-28 21:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从PySide2类到qml接口发送包含动态创建qml对象所需的数据的字典,因为我需要响应某些事件,所以需要使用信号和插槽。在

因为我刚刚开始使用QML和python,所以我尝试创建一个简单的项目来玩玩(从代码中可以看到)

质量管理:

import QtQuick 2.10
import QtQuick.Controls 2.2
import QtQuick.Window 2.2
import QtQuick.Controls.Material 2.3
import QtQuick.Layouts 1.0

ApplicationWindow {
    id: mainWindow
    width:640
    height: 480
    title: qsTr("Simple ui")
    visible: true
    locale:locale
    Rectangle {
        id: appWindow
        objectName: "splasso"
        anchors.fill: parent
        color: "yellow"
        Material.accent: Material.DeepPurple
        Material.primary: Material.Cyan
        Component.onCompleted: function(){
            TestVar.theSignal.connect(catchAnswer);
            testList.append(stuff1);
            testList.append(stuff2);
            testList.append(stuff3);
            testCombo.currentIndex = 0;
            //Just a pointless test print
            console.log(JSON.stringify(stuff1));
        }
        function catchAnswer(answer){
            console.log(JSON.stringify(answer));
        }

        ComboBox{
            id: testCombo
            anchors.centerIn: parent
            width: parent.width
            onCurrentIndexChanged: function(){
                TestVar.catchInt(currentIndex);
            }

            model: ListModel{
                id: testList
            }
        }
    }
}

Python 3:

^{pr2}$

我期望的输出(使用“python3 Test_dict_1.py”启动脚本)是:

Caught: 1
qml: {"myAnswer": 1}
Caught: 2
qml: {"myAnswer": 2}
Caught: 1
qml: {"myAnswer": 1}
...etc...

我得到的是:

Caught: 1
qml: undefined.
Caught: 2
qml: undefined.
Caught: 1
qml: undefined.
...etc...

你能告诉我我做错了什么吗?是代码有错误还是这件事做不到?在


Tags: 代码importidfunctionqmlwidthparentmaterial
1条回答
网友
1楼 · 发布于 2024-09-28 21:49:29

必须在信号中使用的签名是QVariant

class Test1(QObject):
    theSignal = Signal('QVariant')

    @Slot(int)
    def catchInt(self,caught):
        print("Caught: {0}".format(caught))
        testDict = {"myAnswer":caught}
        self.theSignal.emit(testDict)

相关问题 更多 >