Qt on Android: Basic QML Language

Source: Internet
Author: User
Tags javascript array

The QML syntax is similar to Json in Qt on Android: Qt Quick introduction. For details, refer to Qt on Android: http download and Json parsing to view Json syntax. Of course we want to learn QML from scratch, so you can also look down directly.

Object

The suffix of the QML file is qml, which is actually a text file. The following is a simple QML file:

import QtQuick 2.0import QtQuick.Controls 1.1import QtQuick.Dialogs 1.1import an.qt.ImageProcessor 1.0import QtQuick.Controls.Styles 1.1Rectangle {    width: 320;    height: 480;    color: "#121212";        Image {        source: "images/IMG_001.jpg";        anchors.centerIn: parent;    }}

The start of this simple QML file is the import Statement. For example, import QtQuick 2.0 introduces the QtQuick 2.0 module. Wow, it's really nonsense! Let's talk nonsense. Import is similar to # include in C ++. It has the same effect as the import in Java ...... Tang Miao.

The Rectangle {} statement defines an object of the Rectangle type. If you read the Json syntax description in Qt on Android: http download and Json parsing, you should already know that the object should be described with a pair of curly brackets. Yes, this is also true in QML. However, you need to write the object type before curly braces. That's easy!

The example QML document contains two objects: Rectangle and Image.

Between curly braces, It is the property description of the object (there can be other such descriptions later). The property is specified in the form of "property: value", which is the same as Json. As you can see, the Rectangle object has attributes such as width and color.

Attributes can be written in different branches. Do not use ";" after the statement, but I suggest adding ";" to C ++ programmers to avoid schizophrenia. Of course, you can also write multiple attributes in one row. Multiple Attributes must be separated. As follows:

Rectangle {    width: 320; height: 480; color: "#121212";}
I strongly recommend that you do not do this! Unless there is an unexpected reason for the Code, such as typographical needs, for example, the boss thinks that you have too many lines of code ......
Expression

As mentioned in introduction to Qt on Android: Qt Quick, QML supports JavaScript expressions. For example, you can rewrite the width and height attributes of a Rectangle object as follows:

Rectangle {    width: 23*10;     height: 6*80;     color: "#121212";}

I just said, you may not write this in your actual project. This kind of behavior is hard to hear ...... Of course, I can also give a meaningful example:

Button {    text: "Quit";    style: ButtonStyle {        background: Rectangle {            implicitWidth: 70;            implicitHeight: 25;            border.width: control.activeFocus ? 2 : 1;        }    }}

In this example, I specify the background rectangle in the button style. When the button has focus, the Border width is 2 and the width is 1 if there is no focus. Statement "border. width: control. activeFocus? 2: 1 "using JavaScript "? : "Sanyuan cloud algorithm (C ++ also seems to have ......).

In addition, as you may have noticed, the above expression uses "control. activeFocus". Yes, other objects and their attributes can be referenced in the expression. When you do this, the attribute to be assigned is associated with the attribute of the object you reference. When the referenced attribute changes, the value of the expression is recalculated, the attributes to be assigned change.

Maybe you already have a question: how to reference an object? The answer is: Reference an object by its id value. Here:

Rectangle {width: 320; height: 480; Button {id: openFile; text: "Open"; anchors. left: parent. left; anchors. leftMargin: 6; anchors. top: parent. top; anchors. topMargin: 6;} Button {id: quit; text: "quit"; anchors. left: openFile. right; anchors. leftMargin: 4; anchors. bottom: openFile. bottom ;}}


In the preceding example, the exit button uses the id (openFile) to reference the OPEN button.

What is anchors ...... Leave it alone, and we will talk about it in the next article.

Note

In QML, the comment is the same as in C ++. A single row starts with "//", and multiple rows start with "/*" and end.

Annotations are not executed. You can add annotations to explain the code or improve readability. Annotations can also be used to prevent code execution, which is useful for tracking problems.

Sample QML with annotations:

/** The root element of QML */Rectangle {width: 320; height: 480; Button {id: quit; text: "quit"; // use anchors to layout anchors. left: openFile. right; anchors. leftMargin: 4; anchors. bottom: openFile. bottom; // set z-order z: 1 ;}}

Attribute

In fact, attributes in QML are member variables in C ++ that we are very familiar ......

Attribute name

The first letter of the attribute name generally starts in lower case. For example, we can see the annoying width attribute.

If the attribute name is represented by multiple words, the second and subsequent words are capitalized.

Attribute type

There are about three types that can be used in the QML document:

The type provided by the QML language. Use the QML module to register the C ++ type. The type provided by the QML module.

Let's first look at the basic types provided by the QML language.

Basic Type

The basic types supported by QML include integer, real number, Boolean, String, color, and list. Some of these basic types correspond to the basic types of JavaScript language.

In the previous example, we modified it and annotated the property type:

Rectangle {width: 320; // int height: 480; Button {id: quit; text: "quit"; // string anchors. left: openFile. right; anchors. leftMargin: 4; anchors. bottom: openFile. bottom; z: 1.5; // real visible: false; // bool }}

Note that attributes in QML have type security detection. That is to say, you can only specify the value that matches the attribute type. Otherwise, an error is returned.

Use the Index Mode of the Qt assistant to search for the "qml basic types" keyword and find the QML Basic Types page to view the complete type list and details of each type.

The QML module of Qt has not introduced many Qt-related types, such as Qt, QtObject, Component, Connections, and Binding. Use the Qt assistant to search for "qt QML qml types.

Id attribute

I mentioned the id Attribute before the expression. Here we will describe it.

The id attribute of an object is unique and the values of the id attribute of different objects in the same QML file cannot be repeated. If an object is specified with an id, the object can be referenced by id in other objects or scripts. In the expression section, we have demonstrated how to reference an object by id.

Note that the value of the id attribute must start with a lowercase letter or underline and cannot contain letters, numbers, or underscores.

List attributes

The list attributes are similar to the following:

Item {    children:[        Image{},        Text{}    ]}

A list is a list element that is enclosed in square brackets and separated by commas. Does it seem familiar? In Qt on Android: http download and Json parsing, let's take a look at the example of a Json array:

[  "name":"zhangsan",   {    "age":30,    "phone":"13588888888",    "other": ["xian", null, 1.0, 28]  }]

In fact, the list is similar to the JavaScript array, and its access method is also the same:

The length attribute provides the number of elements in the list. Elements in the list are accessed by array subscript ([index]).

It is worth noting that the list can only contain QML objects and cannot contain any basic types (such as integer and Boolean types ). This is different from Json. The following is an example of an access list:

Item {    children:[        Text{            text: "textOne";        },        Text{            text: "textTwo";        }    ]    Component.onCompleted:{                for (var i = 0; i < children.length; i++)            console.log("text of label ", i, " : ", children[i].text)    }}

If you have only one element in a list, square brackets can also be omitted. As follows:

Item {    children:Image{}}


However, we recommend that you always use square brackets, even if there is only one element.

Is there any problem? I want to talk about it. If you're bored, you may feel bad about yourself. Okay, I will do it if you don't. In our access list example, a new content is displayed, Component. onCompleted :{}. What is this? Next, let's talk about it.

Signal Processor

The signal processor is equivalent to the slot in Qt. However, we do not see functions that are clearly defined in C ++ ...... That's right. You actually only saw a pair of curly braces! This is a code block in JavaScript. Actually, you can understand it as an anonymous function. Functions in JavaScript are actually named code blocks. The benefit of a function is that you can call it by name elsewhere, and the benefit of a code block is that no one can call it except for defining it. In a word, it is private. A code block is a combination of a series of statements. It is used to execute statement sequences together.

Let's look back at the Signal processor. Its name is a bit special, generally in the form of on {Signal. For example, if the Button element in Qt Quick has a signal clicked (), you may write the following code:

Rectangle {width: 320; height: 480; Button {id: quit; text: "quit"; anchors. left: parent. left; anchors. leftMargin: 4; anchors. bottom: parent. bottom; anchors. bottomMargin: 4; onClicked: {Qt. quit ();}}}

The above QML code is actually a simple QML application. This application adds an exit button in the lower left corner of the window. When you click it, the clicked () signal of the button is triggered, we define a signal processor to respond to the clicked () signal-call Qt. quit () exits the application.

As you can see, when the signal is clicked (), the signal processor is named onClicked. This is simple, with the start of on followed by the signal name (the first letter in uppercase ).

Group attributes

In some cases, a '.' or a group symbol is used to form a logical group of related attributes. The group attributes can be written as follows:

Text {    font.pixelSize: 18;    font.bold: true;}

You can also write as follows:

Text {    font { pixelSize: 12; bold: true; }}

In fact, it can be understood that the font attribute type itself is an object, and this object has properties such as pixelSize/bold/italic/underline. You can use ". "operator expands the value assigned to each member of an object. You can also put the Members to be assigned together by grouping symbols (a pair of curly brackets) to assign values to them. For the latter, its form is the same as the definition of the object, at least it looks like wood is different. So we can understand the above example: the Text object aggregates the font object. OK, that is, aggregation.

Additional attributes

Attribute is really difficult! Not only have you been bored, but I cannot sit down. I promise that this is the last point, but it is also the most complex and incomprehensible attribute. For this kind of things, I always accept it if I can't understand it. When it is born, it is reasonable to exist. As long as you learn how to use it, you will be OK.

In the syntax of the QML language, there is an additional Property (attached properties) and the concept of an additional signal processor (attached signal handlers), which is an additional Property attached to an object. Essentially, these attributes are implemented and provided by the attaching type and may be attached to another type of object. The difference between an additional property and a common property is that the common property of an object is provided by the object itself or its base class (or ancestor who traces back along the inheritance level.

For example, the following Item object uses additional attributes and additional signal processors:

import QtQuick 2.0Item {    width: 100;     height: 100;    focus: true;    Keys.enabled: false;    Keys.onReturnPressed: console.log("Return key was pressed");}

You can see that the Item object can access and set the values of Keys. enabled and Keys. onReturnPressed. Enabled is an attribute of the Keys object. OnReturnPressed is actually a signal of the Keys object. The additional signal processor is different from the common signal processor mentioned above. For a common Signal processor, you must first know the Signal name, and then define the name of the Signal processor according to the on {Signal} syntax. For a Signal processor, you only need to reference it through the additional type name, assign the code block to it.

Finally, let's talk about the Keys object, which is provided by Qt Quick for the Item to process key events. It defines many signals for specific buttons, such as the onReturnPressed above, and also defines more common onPressed and onReleased signals. Generally, you can use these two signals to process keys (refer to keyPressEvent and keyReleaseEvent in Qt C ++ ). They have a KeyEvent parameter named "event", which contains detailed information about the buttons. If a key is processed, event. accepted should be set to true to prevent it from being transmitted.

The following is an example of using the onPressed signal, which detects the left direction key:

Item {    anchors.fill: parent;    focus: true;    Keys.onPressed: {        if (event.key == Qt.Key_Left) {            console.log("move left");            event.accepted = true;        }    }}


Well, the basic introduction to the QML language is here. I believe you can now understand the simple QML documentation. Some may have some questions. I have some other things I just don't want to talk about, such as Rectangle/Text/Image/Item/Button/Component/Qt. Sorry, now we can only get confused about these things. We will talk about these things in the next article.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.