One of the first questions I hear once people start using QML is if there is a way to do class inheritance in QML. Its an understandable question; as you start using QML you’ll undoubtedly find your self writing components that have comment elements and want to find a way to reduce duplicate code.
First I was answering that question with no sorry, can’t be done. I did however noticed that Composition was possible. The other day however I kind of had an ah ha moment and realized that yes QML elements can employ both is a and has a constructs.
Has A: Composition
In QML Composition is the name of the game; that is any element in QML by nature of the declarative language can have internally other elements. A super element can be created by consuming child elements to create new functionality.
Here the new element, SuperElement is a composition of a BaseElement, Text element and a Rectangle element; in other words the SuperElement has a BaseElement, has a Text element, and has a Rectangle element. Thus providing consumers with something new that extends the functionality of the BaseElement.
Is A: Inheritance
In QML Inheritance can be achieved by instead of having the child element contain a base element have it be the base element that gets extended by the child element script. That is new functionally can be created by having a child element extend the base element.
Here the new element, ChildElement is a BaseElement; however, it extends the Baseelement by adding a Text element and a Rectangle element. Thus providing consumers with something new that extends the functionality of the BaseElement.
So there you have it QML does in fact support both Composition and class inheritance; it might be a subtle difference in the code but does make a big difference conceptually.
Until next time think imaginatively and design creatively