Quick Start Guide - QML Basics
Creating a QML Document
A QML document defines a hierarchy of objects with a highly-readable, structured layout. Every QML document consists of two parts: an imports section and an object declaration section. The types and functionality most common to user interfaces are provided in the QtQuick import.
Importing and Using the QtQuick Module
To use the QtQuick module, a QML document needs to import it. The import syntax looks like this:
import QtQuick 2.0
The types and functionality that QtQuick provides can now be used in the QML document!
Defining an Object Hierarchy
The object declaration in a QML document defines what will be displayed in the visual scene. QtQuick provides the basic building blocks for all user interfaces, including objects to display images and text, and to handle user input.
A simple object declaration might be a colored rectangle with some text centered in it:
Rectangle { width: 200 height: 100 color: "red" Text { anchors.centerIn: parent text: "Hello, World!" } }
This defines an object hierarchy with a root Rectangle object which has a child Text object. The parent of the Text object is automatically set to the Rectangle, and similarly, the Text object is added to the children property of the Rectangle object, by QML.
Putting it Together
The Rectangle and Text types used in the above example are both provided by the QtQuick import. To use them, we need to import QtQuick. Putting the import and object declaration together, we get a complete QML document:
import QtQuick 2.0 Rectangle { width: 200 height: 100 color: "red" Text { anchors.centerIn: parent text: "Hello, World!" } }
If we save that document as "HelloWorld.qml" we can load and display it.
Loading and Displaying the QML Document
To display the graphical scene defined by the QML document, it may be loaded with the qmlscene tool. The qmlscene tool should be installed into the Qt installation directory. Assuming that the Qt binaries are installed into or are available in the system executable path, you can display the QML document with the following command:
qmlscene HelloWorld.qml
You should see the text "Hello, World!" in the center of a red rectangle.