Published on Mar 07, 2021 by Elias Steurer | Kelteseth
You can click on the image to edit the example live in your browser!
Every QML file must contain exactly one root item (and some imports to get the functionality we need, but we just have to accept this for now). In this example we use an QML Item as our root element. An
Item is the base type of all QML components. You can think about it as an invisible rectangle that also has many more features like position, opacity, focus etc. and most important an
id to be identified.
Id must be unique in QML but are not mandatory.
anchors to easily position a component in the scene without manual logic. The line
anchors.fill: parent simply states to have the same
height as the parent element. The parent element of the root here is our Window.
If you actually want a rectangle with a color you can use the type QML Rectangle for this. In this example we created a
Rectangle as a child of our main Item. This
Rectangle inherits all properties of the Item like
id etc. We set the
width to be calculated from the root items width multiplied by 0.5. We now can use the defined
id root and access the property via the dot notation. In the next line we set the
height to the same value as our
width by simply binding the value. Bindings are a powerful feature, making writing even more complex interactions a breeze. The next two properties define the position relative to the parent element. The last property is the color of our Rectangle. This can be a color string like
"orange" or a hex value
A important QML component is the QML Text type. As the name describes we use this to draw text. Text like Rectangle inherits all features from
Item, so it also has the property anchors. The line
anchors.centerIn: parent is actually equal to the code below but way easier to read.
x: root.width / 2 - width / 2 y: root.height / 2 - height / 2
To actually set the text we simply can define a fixed string. We can add a value like the
width of our orange rectangle to our string to show us the
width as a number. For this we simply can add (
+) it to our text. The QML engine keeps track of the values. This means if we resize the window it would also automatically change the text to the new width value.
Creating an empty QML wallpaper via the Create Wizards. Open the containing folder: Now you can simply copy and paste your code in the qml file.
property bindingsto automatically update properties without manually writing code