Extending QML - Inheritance and Coercion Example | Qt QML 6.4.1

- Qt 6.4
- Qt QML
- Qt QML Examples
- Extending QML - Inheritance and Coercion Example
- Qt 6.4.1 Reference Documentation

# Extending QML - Inheritance and Coercion Example

C++ Inheritance and Coercion.

This example builds on:

- Extending QML - Object and List Property Types Example
- Extending QML - Adding Types Example

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

     class Boy : public Person
     {
         Q_OBJECT
         QML_ELEMENT
     public:
         using Person::Person;
     };

     class Girl : public Person
     {
         Q_OBJECT
         QML_ELEMENT
     public:
         using Person::Person;
     };

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.

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.

##### 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.

     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.

#### Running the Example

The BirthdayParty type has not changed since the previous example. The celebrant and guests property still use the People type.

         Q_PROPERTY(Person *host READ host WRITE setHost)
         Q_PROPERTY(QQmlListProperty<Person> 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.

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.

Example project @ code.qt.io