C++ Inheritance and Coercion.
C++继承和强制。
This example builds on:
此示例基于:
The Inheritance and Coercion Example shows how to use base classes to assign types of more than one type to a property. It specializes the Person type developed in the previous examples into two types - a Boy
and a Girl
.
继承和强制示例显示了如何使用基类将多个类型的类型分配给属性。它将前面例子中发展出来的人分为两种类型——男孩和女孩。
BirthdayParty {
host: Boy {
name: "Bob Jones"
shoeSize: 12
}
guests: [
Boy { name: "Leo Hodges" },
Boy { name: "Jack Smith" },
Girl { name: "Anne Brown" }
]
}
Declare Boy and Girl
声明男孩和女孩
QML_ELEMENT
QML_UNCREATABLE("Person is an abstract base class.")
The Person class remains unaltered in this example and the Boy and Girl C++ classes are trivial extensions of it. The types and their QML name are registered with the QML engine.
Person类在本例中保持不变,Boy和Girl C++类是它的简单扩展。类型及其QML名称在QML引擎中注册。
As an example, the inheritance used here is a little contrived, but in real applications it is likely that the two extensions would add additional properties or modify the Person classes behavior.
例如,这里使用的继承有点做作,但在实际应用程序中,这两个扩展可能会添加其他属性或修改Person类的行为。
Define People as a Base Class
将人员定义为基类
The implementation of the People class itself has not changed since the previous example. However, as we have repurposed the People class as a common base for Boy and Girl, we want to prevent it from being instantiated from QML directly - an explicit Boy or Girl should be instantiated instead.
自上一个示例以来,People类本身的实现没有改变。然而,由于我们已经重新调整了People类的用途,将其作为Boy和Girl的公共基础,我们希望防止它直接从QML实例化-应该实例化显式的Boy或Girl。
QML_ELEMENT
QML_UNCREATABLE("Person is an abstract base class.")
While we want to disallow instantiating Person from within QML, it still needs to be registered with the QML engine, so that it can be used as a property type and other types can be coerced to it. This is what the QML_UNCREATABLE macro does.
虽然我们不允许在QML中实例化Person,但它仍然需要在QML引擎中注册,以便它可以用作属性类型,并且可以强制其他类型。这就是QML_UNCREATABLE宏所做的。
Running the Example
运行示例
The BirthdayParty type has not changed since the previous example. The celebrant and guests property still use the People type.
自上一个示例以来,BirthdayParty类型没有更改。celebrant和guests属性仍使用People类型。
Q_PROPERTY(Person *host READ host WRITE setHost)
Q_PROPERTY(QQmlListProperty guests READ guests)
QML_ELEMENT
However, as all three types, Person, Boy and Girl, have been registered with the QML system, on assignment QML automatically (and type-safely) converts the Boy and Girl objects into a Person.
但是,由于所有三种类型Person、Boy和Girl都已在QML系统中注册,分配时QML会自动(并安全地键入)将Boy和Girl对象转换为Person。
The main.cpp file in the example includes a simple shell application that loads and runs the QML snippet shown at the beginning of this page.
示例中的main.cpp文件包括一个简单的shell应用程序,该应用程序加载并运行本页开头显示的QML代码段。