扩展QML(高级)- 继承与强制转换

这是使用生日派对示例来展示QML一些高级功能的6个示例系列中的第二个示例。

目前,每个参与者都被建模为一个人。这有点太笼统了,能够了解更多关于参与者的信息会更好。通过将他们专门化为男孩和女孩,我们已经可以更好地了解谁会来。

为此,引入了BoyGirl类,两者都继承自Person

43
44@QmlElement
45class Boy(Person):
46    def __init__(self, parent=None):
49
50@QmlElement
51class Girl(Person):
52    def __init__(self, parent=None):

Person 类保持不变,BoyGirl 类是其简单的扩展。这些类型及其 QML 名称通过 @QmlElement 注册到 QML 引擎中。

请注意,hostguests 属性在 BirthdayParty 中仍然接受 Person 的实例。

26
46

Person 类本身的实现没有改变。 然而,由于 Person 类被重新用作 BoyGirl 的公共基类,Person 不应再从 QML 直接实例化。应该 显式实例化 BoyGirl

13
14@QmlElement
15@QmlUncreatable("Person is an abstract base class.")

虽然我们希望禁止在QML中实例化Person,但它仍然需要注册到QML引擎中,以便它可以作为属性类型使用,并且其他类型可以强制转换为它。这就是@QmlUncreatable的作用。由于PersonBoyGirl这三种类型都已注册到QML系统中,在赋值时,QML会自动(并且类型安全地)将BoyGirl对象转换为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
from __future__ import annotations

"""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 __future__ import annotations

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 __future__ import annotations

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