Qml set context property for child item
-
I want to set a context property of a Qml Button from PySide6 but I get an error. Here are the relevant files:
import sys from PySide6.QtCore import QObject, Slot from PySide6.QtGui import QGuiApplication from PySide6.QtQml import (QQmlApplicationEngine, QmlElement, QQmlComponent, QQmlContext) QML_IMPORT_NAME = "EventHandlers" QML_IMPORT_MAJOR_VERSION = 1 @QmlElement class EventHandler(QObject): def __init__(self, parent=None): super().__init__(parent) @Slot() def on_button_click(self): print('Button clicked') if __name__ == '__main__': app = QGuiApplication(sys.argv) engine = QQmlApplicationEngine() engine.quit.connect(app.quit) engine.load('view.qml') event_handler = EventHandler() root = engine.rootObjects()[0] button3 = root.findChild(QObject, 'button3') button3.clicked.connect(event_handler.on_button_click) engine.rootContext().setContextProperty('python_handler', event_handler) button5 = root.findChild(QObject, 'button5') button5_context = QQmlContext(engine, button5) button5_context.setContextProperty('evt_handler', event_handler) result = app.exec() del engine sys.exit(result)
view.qml:
import QtQuick import QtQuick.Controls import QtQuick.Layouts import EventHandlers ApplicationWindow { visible: true width: 200 height:400 title: "HelloApp" EventHandler { id: eventHandler } ColumnLayout { id: layout objectName: "layout" anchors.fill: parent Button { id: button1 Layout.fillWidth: true Layout.fillHeight: true text: "Qml event handler" onClicked: console.log("Button clicked") } Button { id: button2 Layout.fillWidth: true Layout.fillHeight: true text: "PySide -> Qml event handler" onClicked: eventHandler.on_button_click() } Button { id: button3 objectName: "button3" Layout.fillWidth: true Layout.fillHeight: true text: "Qml -> PySide event handler" } Button { id: button4 objectName: "button4" Layout.fillWidth: true Layout.fillHeight: true text: "Root context event" onClicked: python_handler.on_button_click() } Button { id: button5 objectName: "button5" Layout.fillWidth: true Layout.fillHeight: true text: "Child context event" onClicked: evt_handler.on_button_click() } } }
The error I get:
view.qml:63: ReferenceError: evt_handler is not defined
Why this no work? The root context property work fine but button5 (last button) cannot set context property