QML: Component vs Item as a container

10,296

Solution 1

The difference between those two snippets is that the Rectangle will be immediately displayed. This is written in the documentation:

Notice that while a Rectangle by itself would be automatically rendered and displayed, this is not the case for the above rectangle because it is defined inside a Component. The component encapsulates the QML types within, as if they were defined in a separate QML file, and is not loaded until requested (in this case, by the two Loader objects). Because Component is not derived from Item, you cannot anchor anything to it.

When declaring delegates, Component is used because there are several delegate items that must be created. A single Item doesn't work here. You can think of Component as a template that you can create objects from.

Solution 2

A Component is both a concept and a thing in QML. An Item is a visual thing defined in QtQuick module which is usable in QML. These two things are conceptually different.

As a QML concept, all reusable things are called components. You can define a component in multiple ways, but one easy way is to create a .qml file and name it as you name your component. i.e: Button.qml or Switch.qml. When the QML engine loads that file, you can use it as buttons or switches.

Another way to define a component is to use Component {} in a .qml file. This allows you to define a new component inline. A component defined inline does not work after explicitly loaded by a loader.

An Item, on the other hand, is a simple type defined in the QtQuick module.

I think it is OK to call an Item a Component even though an Item is not technically inherited from Component. Or more precisely, you could say your custom component is based on an Item if your .qml has Item as a root type.

Share:
10,296
Dmitry
Author by

Dmitry

Updated on June 06, 2022

Comments

  • Dmitry
    Dmitry about 2 years

    What is the difference between Component and Item in QML ? The documentation is not absolutely clear here. What is the preferred type to use as a container for several widgets? Can it be replacable by Rectangle?

    For example, what is the difference in the following declarations:

    Item {
        id: itemWidget
    
        Rectangle { id: one }
        Rectangle { id: two }
    }
    

    and

    Component {
        id: componentWidget
    
        Rectangle { id: one }
        Rectangle { id: two }
    }
    

    Why do we usually use Component when declaring a delegate?