Qml, Reference error <signalName> is not defined when signal defined

Question:

I have a very simple qml+python app to play and test signal/slot communication.

All works fine so far, but when I run the app, a ReferenceError is reported on the QML side.

However, all works fine, it is so simple code:

QML:

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

Python:

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

Why do I keep getting the error:

ReferenceError: signalEmitter is not defined 

on line 12 in qml file. (app runs and signal/slot works as expected)

Asked By: codeKiller

||

Answers:

You should add the context properties before loading any 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())
Answered By: Amfasis
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.