QML Tutorial


Foreword

A version of Qt4 with QML support has been released for a long time. Since then, much has been added and now the technology is quite successful and stable. However, a normal description could not be found in Russian. And in English it is written as they say, “with the right hand, and the left ear.” Therefore, I decided to start translating the tutorial (so far the basic one, then I plan to expand it) into Russian. Actually, you can find a tutorial on my GitHub or here below.

QML Tutorial

This tutorial provides an introduction to QML (Qt Quick Interface Language). It does not cover everything – the emphasis is on teaching the basic principles, and features and additions are given as needed.

In this tutorial, you’ll learn about the basic QML types, create your own QML component with properties and signals, and create simple animations using states and transitions.

The first chapter starts with a minimal “Hello World” program, and new concepts are introduced in later chapters.

The source codes from the manual are located in the Qt directory:

examples/quick/tutorials/helloworld

Leadership chapters:

  1. Base Types

  2. QML Components

  3. States and Transitions

Chapter 1 – Basic Types

The first program is a very simple “Hello world” example that will introduce you to some basic QML concepts.

The figure below shows a screenshot of this program:

QML application code:

import QtQuick 2.0

Rectangle {
    id: page
    width: 320; height: 480
    color: "lightgray"

    Text {
        id: helloText
        text: "Hello world!"
        y: 30
        anchors.horizontalCenter: page.horizontalCenter
        font.pointSize: 24; font.bold: true
    }
}

Parsing by steps

Import

First you need to import the types you need for this example. Most QML files import built-in QML types (for example, Rectangle, Image…) that come with Qt using:

import QtQuick 2.0

Type – Rectangle

Rectangle {
    id: page
    width: 320; height: 480
    color: "lightgray"

Here the root object of type is declared Rectangle (Rectangle). This is one of the basic building blocks that you can use to create a QML application. Next, it is assigned an identifier so that it can be referred to in the future. In this case, the ID is “page”. The width, height, and color properties are also set. Type of Rectangle contains many other properties (such as x and y), but they will be initialized with default values.

Type – Text

Text {
    id: helloText
    text: "Hello world!"
    y: 30
    anchors.horizontalCenter: page.horizontalCenter
    font.pointSize: 24; font.bold: true
}

Type is added here Text as a child element of the Rectangle root type, which displays the text “Hello world!”.

Property y used to position text vertically at a distance of 30 pixels from the top of its parent element.

Property anchors.horizontalCenter applied to the horizontal center of the type. In this case, it specifies that the Text type should be horizontally centered on the “page” element (see below). Anchor-Based Layout).

The size font.pointSize and font.bold associated with fonts and use dot notation.

Viewing an example

To view what you have created, run the tool qml (located in the bin directory) with your filename as the first argument. For example, to run the provided completed Chapter 1 example from the installation location, you would type:

qml tutorials/helloworld/tutorial1.qml

Chapter 2 – QML Components

This chapter describes the tool for changing the text color.

The screenshot above shows a color set consisting of six cells with different colors. To avoid repeating the same code for each cell, a new cell component (component cell). The component provides a way to define a new type that can be reused in other QML files. A QML component is like a black box and interacts with the outside world through properties, signals, and functions, and is usually defined in its own QML file. (cm. Component Documentation). The component file name must always begin with a capital letter of the English alphabet.

Below is the QML code for Cell.qml:

import  QtQuick 2.0
  
Item {
   id: container
   property alias cellColor: rectangle.color
   signal clicked(cellColor: color)

   width: 40; height: 25

   Rectangle {
      id: rectangle
      border.color: "white"
      anchors.fill: parent
   }

   MouseArea {
      anchors.fill: parent
      onClicked: container.clicked(container.cellColor)
   }
}

Parsing by steps

Cell component

Item {
   id: container
   property alias cellColor: rectangle.color
   signal clicked(cellColor: color)

   width: 40; height: 25

The root type of our component is element (item) with identifier (ID) equal to container. Element (item) is the most basic visual type in QML and is often used as a container for other types.

property  alias  cellColor:  rectangle.color

The property is declared above cellColor (cell color). This property is available from outside the component, it allows you to instantiate cells with different colors. This property is simply an alias for the existing property, the color of the rectangle that makes up the cell (see below). Property binding).

signal clicked(cellColor: color)

We also need our component to have a signal that we call when it is clicked (clicked) with a color type cell color parameter (color). Later we will use this signal to change the color of the text in the main QML file.

Rectangle {
   id: rectangle
   border.color: "white"
   anchors.fill: parent
}

The cell component is basically a colored rectangle with an id (ID) rectangle.

Property anchors.fill is a convenient way to set the size of a visual type. In this case, the rectangle will have the same size as its parent element (see below). Anchor-based layout).

MouseArea {
   anchors.fill: parent
   onClicked: container.clicked(container.cellColor)
}

To change the text color when a cell is clicked, a type is created MouseArea (mouse area) with the same size as its parent.

Main QML file

The main QML file uses the previously created Cell component to create a color picker:

import QtQuick 2.0

Rectangle {
   id: page
   width: 320; height: 480
   color: "lightgray"
   
   Text {
      id: helloText
      text: "Hello world!"  
      y: 30
      anchors.horizontalCenter: page.horizontalCenter
      font.pointSize: 24; font.bold: true
   }

   Grid {
      id: colorPicker
      x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
      rows: 2; columns: 3; spacing: 3

      Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
      }
}

A color picker is created, representing a grid of 6 cells with different colors.

When the mouse click signal is fired (clicked signal) by cell, the text color will be set to the color of the cell passed as a parameter cellColor. We can react to any signal to our component using a property named ‘onSignalName’ (cm. Signal Attributes).

Chapter 3 – States and Transitions

In this chapter, the previous example will become a bit more dynamic using states and transitions.

We want the text to move to the bottom of the screen, rotate and turn red when clicked.

Below is the QML code:

import QtQuick 2.0

Rectangle {
   id: page
   width: 320; height: 480
   color: "lightgray"

   Text {
      id: helloText
      text: "Hello world!"
      y: 30
      anchors.horizontalCenter: page.horizontalCenter
      font.pointSize: 24; font.bold: true

      MouseArea { id: mouseArea; anchors.fill: parent }

      states: State {
         name: "down"; when: mouseArea.pressed == true
         PropertyChanges {
            helloText {
               y: 160
               rotation: 180
               color: "red"
            }
        }
      }  

      transitions: Transition {
         from: ""; to: "down"; reversible: true
         ParallelAnimation {
            NumberAnimation { properties: "y,rotation"; duration: 500; easing.type: Easing.InOutQuad }
            ColorAnimation { duration: 500 }
         }
      }
   }

   Grid {
      id: colorPicker
      x: 4; anchors.bottom: page.bottom; anchors.bottomMargin: 4
      rows: 2; columns: 3; spacing: 3

      Cell { cellColor: "red"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "green"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "blue"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "yellow"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "steelblue"; onClicked: helloText.color = cellColor }
      Cell { cellColor: "black"; onClicked: helloText.color = cellColor }
   }
}

Parsing by steps

states: State {
   name: "down"; when: mouseArea.pressed == true
   PropertyChanges {
      helloText {
         y: 160
         rotation: 180
         color: "red"
      }
   }
}

First a new state is created down for text type. This state will be activated when the mouse button is pressed and deactivated when it is released.

State down includes a set of property changes from an implicit default state (elements as originally defined in QML). Manually (on purpose) the text properties are set equal to: vertical position (y) is 160, rotation is 180, and color is red.

transitions: Transition {
   from: ""; to: "down"; reversible: true
   ParallelAnimation {
      NumberAnimation { properties: "y,rotation"; duration: 500; easing.type: Easing.InOutQuad }
      ColorAnimation { duration: 500 }
  }
}

To make the text appear below not instantly, but move smoothly, a transition is added between our two states.

“from” and “to” define the states between which the transition will be performed. In this case, there is a transition from the default state to the state down.

Since it is required that the same transition be executed in reverse order when returning from the state down to the default state, we set reversable to true. This is equivalent to writing two transitions separately.

Type of ParallelAnimation ensures that two animation types (number and color) run at the same time (in parallel). It would also be possible to run them one by one, using instead SequentialAnimation.

For more information about states and transitions, see QtQuick Statesas well as An example of implementing states and transitions.

Afterword

I decided to post this tutorial-self-study here, because. GitHub began to block the repositories of Russian companies and, who knows, it may start banning ordinary people as well. And Habr is ours, dear.

The second point is that the author of this translation (that is, me) is not a professional translator, so errors may be present. Thanks for understanding.

And finally, I can’t help but say that the original tutorial can be found on the official Qt website. Everything, rights reserved and blah blah blah.

© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and their respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *