扩展QML(高级)- 继承和转换#
这是6例教程系列中的第二个示例,使用生日派对作为示例来展示一些QML的高级功能。
目前,每位参与者都被模拟为一个人。这有点太通用,而且最好能够更多地了解参与者。通过将他们区分为男孩和女孩,我们可以更好地了解谁会来。
要做到这一点,引入了Boy
和Girl
类,它们都继承自Person
。
43@QmlElement
44class Boy(Person):
45 def __init__(self, parent=None):
46 super().__init__(parent)
49@QmlElement
50class Girl(Person):
51 def __init__(self, parent=None):
52 super().__init__(parent)
Person
类保持不变,Boy
和Girl
类是它的简单扩展。类型及其QML名称通过@QmlElement
注册到QML引擎中。
注意,在BirthdayParty
中,host
和guests
属性仍然接受Person
的实例。
26 @Property(Person, notify=host_changed, final=True)
46 guests = ListProperty(Person, appendGuest, notify=guests_changed, final=True)
《Person》类的实现并未改变。然而,由于《Person》类被重新用于作为《Boy》和《Girl》的通用基类,因此《Person》不应再直接从 QML 中实例化。应显式实例化《Boy》或《Girl》。
13@QmlElement
14@QmlUncreatable("Person is an abstract base class.")
15class Person(QObject):
虽然我们希望阻止在 QML 中实例化《Person》,但《Person》仍然需要登记到 QML 引擎,以便可以使用它作为属性类型以及其他类型可以被强制转换为它。这正是《@QmlUncreatable》宏所做的事情。由于三种类型,《Person》、《Boy》和《Girl》,都已在 QML 系统中登记,在赋值时,QML 会自动(并且类型安全地)将《Boy》和《Girl》对象转换为《Person》。
实现了这些更改后,我们现在可以指定生日派对,并提供有关参加者的额外信息,如下所示。
6BirthdayParty {
7 host: Boy {
8 name: "Bob Jones"
9 shoe_size: 12
10 }
11 guests: [
12 Boy { name: "Leo Hodges" },
13 Boy { name: "Jack Smith" },
14 Girl { name: "Anne Brown" }
15 ]
16}
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
"""PySide6 port of the
qml/examples/qml/tutorials/extending-qml-advanced/advanced2-Inheritance-and-coercion example
from Qt v6.x"""
from pathlib import Path
import sys
from PySide6.QtCore import QCoreApplication
from PySide6.QtQml import QQmlComponent, QQmlEngine
from person import Boy, Girl # noqa: F401
from birthdayparty import BirthdayParty # noqa: F401
app = QCoreApplication(sys.argv)
engine = QQmlEngine()
engine.addImportPath(Path(__file__).parent)
component = QQmlComponent(engine)
component.loadFromModule("People", "Main")
party = component.create()
if not party:
print(component.errors())
del engine
sys.exit(-1)
host = party.host
print(f"{host.name} is having a birthday!")
if isinstance(host, Boy):
print("He is inviting:")
else:
print("She is inviting:")
for g in range(party.guestCount()):
name = party.guest(g).name
print(f" {name}")
del engine
sys.exit(0)
# Copyright (C) 2023 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PySide6.QtCore import QObject, Property, Signal
from PySide6.QtQml import QmlElement, ListProperty
from person import Person
# To be used on the @QmlElement decorator
# (QML_IMPORT_MINOR_VERSION is optional)
QML_IMPORT_NAME = "People"
QML_IMPORT_MAJOR_VERSION = 1
@QmlElement
class BirthdayParty(QObject):
host_changed = Signal()
guests_changed = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self._host = None
self._guests = []
@Property(Person, notify=host_changed, final=True)
def host(self):
return self._host
@host.setter
def host(self, h):
if self._host != h:
self._host = h
self.host_changed.emit()
def guest(self, n):
return self._guests[n]
def guestCount(self):
return len(self._guests)
def appendGuest(self, guest):
self._guests.append(guest)
self.guests_changed.emit()
guests = ListProperty(Person, appendGuest, notify=guests_changed, final=True)
# Copyright (C) 2022 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
from PySide6.QtCore import QObject, Property, Signal
from PySide6.QtQml import QmlElement, QmlUncreatable
# To be used on the @QmlElement decorator
# (QML_IMPORT_MINOR_VERSION is optional)
QML_IMPORT_NAME = "People"
QML_IMPORT_MAJOR_VERSION = 1
@QmlElement
@QmlUncreatable("Person is an abstract base class.")
class Person(QObject):
name_changed = Signal()
shoe_size_changed = Signal()
def __init__(self, parent=None):
super().__init__(parent)
self._name = ''
self._shoe_size = 0
@Property(str, notify=name_changed, final=True)
def name(self):
return self._name
@name.setter
def name(self, n):
if self._name != n:
self._name = n
self.name_changed.emit()
@Property(int, notify=shoe_size_changed, final=True)
def shoe_size(self):
return self._shoe_size
@shoe_size.setter
def shoe_size(self, s):
self._shoe_size = s
@QmlElement
class Boy(Person):
def __init__(self, parent=None):
super().__init__(parent)
@QmlElement
class Girl(Person):
def __init__(self, parent=None):
super().__init__(parent)
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
import People
BirthdayParty {
host: Boy {
name: "Bob Jones"
shoe_size: 12
}
guests: [
Boy { name: "Leo Hodges" },
Boy { name: "Jack Smith" },
Girl { name: "Anne Brown" }
]
}
module People
typeinfo coercion.qmltypes
Main 1.0 Main.qml