QML Component Loading¶
This example shows how to load a QML-defined type from Python with
load_qml_component and use it by composition
instead of inheritance.
person.qml defines a Person type with name and age
properties, a birthdayHappened signal, and a celebrateBirthday
method. The Python Employee class composes a Person instance,
connects to its signal, and calls its method:
class Employee:
"""Plain Python class composing a QML Person object."""
def __init__(self, person_factory, name, age, department):
self.person = person_factory.create(name=name, age=age)
self.department = department
self.person.birthdayHappened.connect(self._on_birthday)
def _on_birthday(self):
print(f"{self.person.name} is now {self.person.age}!")
def celebrate(self):
self.person.celebrateBirthday()
"""Load and drive a QML-defined type from Python via load_qml_component.
A ``Person`` type defined in ``person.qml`` is composed inside a plain
Python ``Employee`` class; its QML signal is connected to a Python slot
and its QML method is called from Python.
"""
import sys
from pathlib import Path
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtQmlFeatures import load_qml_component
class Employee:
"""Plain Python class composing a QML Person object."""
def __init__(self, person_factory, name, age, department):
self.person = person_factory.create(name=name, age=age)
self.department = department
self.person.birthdayHappened.connect(self._on_birthday)
def _on_birthday(self):
print(f"{self.person.name} is now {self.person.age}!")
def celebrate(self):
self.person.celebrateBirthday()
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
main_qml = Path(__file__).resolve().parent / "Main.qml"
engine.load(main_qml)
if not engine.rootObjects():
sys.exit(-1)
person = load_qml_component(engine, "person.qml") # create happens in Employee constructor
emp = Employee(person, "Alice", 28, "Engineering")
emp.celebrate() # prints "Alice is now 29!"
sys.exit(app.exec())
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
ApplicationWindow {
width: 400
height: 220
visible: true
title: qsTr("QML Component Loading")
ColumnLayout {
anchors.centerIn: parent
spacing: 16
Label {
text: "A QML Person is created and driven from Python."
Layout.alignment: Qt.AlignHCenter
}
Label {
text: "See the terminal for the composition output."
Layout.alignment: Qt.AlignHCenter
}
}
}
import QtQuick
QtObject {
property string name: "John"
property int age: 30
signal birthdayHappened()
function celebrateBirthday() {
age++
birthdayHappened()
}
}