python Qml,< signalName>定义信号时未定义参考误差

xpcnnkqh  于 2023-02-02  发布在  Python
关注(0)|答案(1)|浏览(140)

我有一个非常简单的qml+python应用程序来播放和测试信号/插槽通信。
到目前为止一切正常,但当我运行应用程序时,QML端报告了一个ReferenceError
然而,一切工作正常,它是如此简单的代码:

质量标记语言:

import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    width: 1000
    height: 480
    visible: true

    title: qsTr("Hello World")

    Connections {
        target: signalEmitter
        ignoreUnknownSignals : true
        function onSignal() {
            console.log("HELLO QML")
        }
    }

    Rectangle{
        height: 100
        width: 100
        color: "green"
        MouseArea {
            anchors.fill: parent
            onClicked: {
                signalEmitter.sayHello()
            }
        }
    }

    Rectangle{
        anchors.fill: parent
        color: "transparent"
        border.color: "black"
    }
}

巨蟒

from PySide6.QtCore import QObject, Signal, Slot
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
import sys

class PythonSignalEmitter(QObject):
    signal = Signal(str)

    @Slot()
    def sayHello(self):
        print("HELLO PYTHON")
        self.signal.emit("HELLO")

if __name__ == '__main__':
    app = QGuiApplication([])
    engine = QQmlApplicationEngine()
    engine.load("main.qml")
    signal_emitter = PythonSignalEmitter()
    engine.rootContext().setContextProperty("signalEmitter", signal_emitter)
    sys.exit(app.exec())

为什么我总是得到错误:

ReferenceError: signalEmitter is not defined

在qml文件的第12行。(应用程序运行,信号/插槽按预期工作)

mpbci0fu

mpbci0fu1#

您应该在加载任何qml之前添加上下文属性:

if __name__ == '__main__':
    app = QGuiApplication([])
    engine = QQmlApplicationEngine()
    signal_emitter = PythonSignalEmitter()
    engine.rootContext().setContextProperty("signalEmitter", signal_emitter)
    engine.load("main.qml") # new place
    sys.exit(app.exec())

相关问题