1

I'm going through a tutorial on QML and they've started using Item as the base for every component they create, after using Rectangle for the first portion of the tutorial.

The thing is, color doesn't seem to be a valid property on Item. I don't understand why.

Then, I looked at a bunch of example component definitions on-line from a variety of places, and they seem to all use Item as the top-level class and then immediately after, Rectangle. What's the point of wrapping a Rectangle in Item? Why not just use Rectangle as the top-level class?

Nejat
  • 31,784
  • 12
  • 106
  • 138
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
  • You should think of `Item` as a base class for all the other components. All other QtQuick types (except windows at the moment) derive from Item (QQuickItem on C++ side). It doesn't have `color`, as it doesn't implement any shape. Sort of unmoulded matter. – W.B. Aug 30 '14 at 09:22

2 Answers2

4

From the Qt documentation :

For creating components (or displaying a simple scene), there are different elements that could be used as the top-level component. To display a simple scene, a Rectangle as the top-level component may suffice. Rectangle, FocusScope, Component, QtObject, Item, are some of the commonly used elements as the top-level component.

So you can have any element as the top level component.

Note that QML visual items like Rectangle, TextEdit, Image, ... inherit from Item . Item is useful for grouping items together. You can use Item to create an invisible container to hold other components. So it facilitates handling children and processing properties such as focus width and height.

I think having Item as the top level component is like having a template for making arbitrary QML components. When your custom component is loaded into another QML scene, the component will retain the top-level component's properties. So you can have a general and non-visual element like Item as the top level item and expose arbitrary properties.

Nejat
  • 31,784
  • 12
  • 106
  • 138
1

You can think of Item as of a non-visual Rectangle that is a bit easier and faster for system to paint as, well, there is nothing to paint. It doesn't really make much difference of whether you use Item or Rectangle as a top level element - it is just a good programming practice not to use more resources than you need.

You will appreciate Item more if you start creating your own non-visual elements at some point.

Artem
  • 776
  • 5
  • 18