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