Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading