Monday, May 27, 2013

Qt QML Introduction and Simple Example Program



QML is declarative language used to develop user interface, is a part of the Qt Quick module. Qt Quick consists of set of technologies including Qml, C++ API's for integrating Qml with Qt application, Qt creator IDE, rum time support.
Qt Quick module comes with the Qt with 4.7 or later versions.

Qml we use elements to draw something on the screen(output) like text, image, rectangle etc.Every element in the qml is like a object. We cal also implement javascript code in side the qml file. Item is the base type for the all the elements.

To start a Qml Application we need to import Qt Quick module with version in the beginning of the every qml file, because the elements we are going to use included in this module. For example the following element displat a rectangle.
Import QtQuick 1.0
Rectangle {
    id: rect
    width: 300
    height: 300
    color: "red"
}

Every element will have properties (with values) to describe it, in the above example id, width, height and color are some properties of the rectangle. The “id” property is used to refer the particular element inside another element. We can put any number of elements inside another element will become child elements.

Proprty binding is the important feature of the qml, means we can use the expression or other properties as the values for the property , so that it will be updated when ever the corresponding proprty updated
Ex: Rectangle {
width: 300
height: width * 2
}
Here height will be updated when ever the width changes
The basic types for the property values are int, real, strings, boolean values, constants, color etc
Comments start with // same as c++ comments.

Writing a First Qt Qml Program:
To start first Qml app follow below
  1. Open Qt Creator
  2. Click on Create Project in File menu (File > New File or Project)
  3. Select Qt Quick Project then Qt Quick Application, then click choose as shown in the following image 

  4. Give the project name and location then click next

  5. Select Built-in elements only (for all platforms) [depending on our requirement]

  6. Then select the target type

  7. Then Click on finish
Note: these steps may slightly change depend on the platform and Qt version

The default main.qml will open with some code (try executing that code), remove the code and write your own code

The following simple Qml program wil change between two colors on clicking on the rectangle
Code: main.qml

// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1

Rectangle {
    id: mainRect
    property bool toggle: false

    width: 360
    height: 360

    MouseArea {
        anchors.fill: parent
        onClicked: {
            console.log("parent")
            toggle = !toggle
            if(toggle)
                mainRect.color = "red"
            else
                mainRect.color = "blue"
        }
    }
}

-->
Output:


No comments:

Post a Comment