QML: Component vs Item as a container
Asked Answered
H

2

30

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?

Honshu answered 5/8, 2015 at 10:30 Comment(3)
What don't you understand about the docs? They can't be improved if you don't say why they aren't clear. I think that they are quite clear, and any answer you get here will most likely be a re-wording of what already exists.Sihun
I agree with @Mitch, the Qt documentation is the best docs I've ever seen so if you found that not clear I think you won't find any help here.Tubman
Added some example to the question descriptionHonshu
S
19

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.

Sihun answered 5/8, 2015 at 11:32 Comment(0)
C
5

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.

Chargeable answered 13/3, 2016 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.