Qt on ANDROID:QML Language basics

Source: Internet
Author: User

In "QT on ANDROID:QT Quick Introduction" We mentioned that QML syntax is similar to JSON, please refer to "qt on android:http Download and JSON parsing" to see the JSON syntax. Of course, we expect to learn QML from scratch, so you can also look straight down.

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 beginning of this simple QML file is an import statement, such as Import QtQuick 2.0, will introduce QtQuick 2.0 module, wow, really nonsense! Go ahead and talk nonsense. Import is similar to #include in C + +, like the import effect in Java, with JavaScript ... Tang, stop.

rectangle{} statement that defines an object of type Rectangle. If you read the syntax description of JSON in the "Qt on android:http Download and JSON parsing" article, you should already know that the object is to be described with a pair of curly braces. Yes, the same is true in QML, but the type of the object to be written before the curly braces. It's so easy!

The example QML document has two objects, one is Rectangle, and the other is an Image.

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

The attribute can be written in a line, at which point the statement may not be ";", but the author suggests that the C + + program ape all Add ";", which will prevent you from suffering from schizophrenia. Of course, you can also write multiple attributes on one line, and multiple attributes must be split with ";". As shown below:

Rectangle {    width:320; height:480; color: "#121212";}
I strongly advise you not to do this! Unless there is a reason for the code to be unexpected, such as the need for typography, such as the boss thinks you have too many lines of code ...
An expression

In the Qt on ANDROID:QT Quick Introduction, the author has mentioned that QML supports JavaScript expressions. For example, you can override the Rectangle object's wide and high attributes:

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

I just motioned, you do not write in the actual project, this kind of behavior is not good to listen to say, a bit of brain residue ... Of course I can also cite 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 a background rectangle in the button style, with a width of 2 without focus when the button has focus, and 1 when the border is not focused. Statement "Border.width:control.activeFocus?" 2:1 "Using JavaScript"?: "Ternary cloud Algorithm (c + + seems to have ...) )。

In addition, as you may have noticed, I used "control.activefocus" in the expression above, yes, other objects and their properties can be referenced in an expression. When you do this, the attribute to be assigned is associated with the property of the object you are referencing, and when the referenced attribute changes, the value of the expression is recalculated, and the property to be assigned changes.

Perhaps you have a question in mind: How to reference an object? The answer is: Refer to an object by its ID value. Look 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: "Exit";        Anchors.left:openFile.right;        Anchors.leftmargin:4;        Anchors.bottom:openFile.bottom;}    }


In the example above, the Exit button uses the ID (openFile) to refer to the Open button.

My good, anchors is what ... Leave it alone, and we'll talk about it in the next article.

Comments

In QML, as in C + +, the single line begins with "//" and multiple lines begin with "/*" and End With "/*".

Comments are not executed, and adding comments can explain or improve the readability of the code. Annotations can also be used to prevent code execution, which is useful for tracking problems.

Example QML for using annotations:

/* The root element of QML */rectangle {    width:320;    height:480;        Button {        id:quit;        Text: "Exit";        Use anchors to layout        anchors.left:openFile.right;        Anchors.leftmargin:4;        Anchors.bottom:openFile.bottom;        Set Z-order        z:1;    }}

Property

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

Attribute naming

The first letter of the property name is usually started in lowercase, such as the width property that we are tired of looking at.

If the property name is expressed in more than one word, the second and subsequent words, capitalized in the first letter.

Property type

There are about three types that you can use in a QML document:

    • Types provided by the QML language itself
    • Registering C + + types using the QML module
    • Types provided by the QML module

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

Basic type

The basic types supported by QML include Integer, Real, Boolean, string, color, list, and so on. Some of these basic types correspond to the basic types of JavaScript languages.

As in the previous example, the property type was annotated with a comment:

Rectangle {    width:320;//int     height:480;        Button {        id:quit;        Text: "Exit"; String        anchors.left:openFile.right;        Anchors.leftmargin:4;        Anchors.bottom:openFile.bottom;        z:1.5; Real        visible:false;//bool    }}

Note that the properties in QML are type-safe, meaning that you can only specify values that match the property type, or you will get an error.

Use the Qt Assistant's indexing mode to search for the keyword "QML basic types", find the QML basic Types page to see the complete type list and each type of detail.

QT's QML module has not QML many of the QT-related types introduced, such as QT, Qtobject, Component, Connections, Binding, etc., please use the QT assistant to retrieve "QT QML QML types" to understand.

ID attribute

The id attribute was mentioned earlier in the introduction of an expression, which is described here.

The ID property of an object is unique, and the value of the id attribute of a different object in the same QML file cannot be duplicated. When an object is assigned an ID, it can be referenced in other objects or scripts by ID. In the "Expressions" section we have shown how to refer to an object by ID.

Note that the value of the id attribute, the first character must be a lowercase letter or an underscore, and cannot contain characters other than letters, numbers, and underscores.

List Properties

The list properties resemble the following:

Item {    children:[        image{},        text{}    ]}

A list is a comma-delimited list element that is contained within square brackets. Does it look familiar? In Qt on android:http download and JSON parsing, we've given examples of JSON arrays, and then look at:

[  "name": "Zhangsan",   {    "age": +,    "phone": "13588888888",    "other": ["Xian", NULL, 1.0,]  } ]

In fact, arrays of lists and JavaScript are similar, and they are accessed in the same way:

    • The Length property provides the number of elements in the list
    • The elements in the list are accessed by an array subscript ([index])

It is important to note that the list can contain only QML objects and cannot contain any basic types (such as integers, booleans). This is not the same as 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, ":", CHI ldren[i].text)    }}

If you have only one element in a list, you can omit the square brackets. As shown below:

Item {    children:image{}}


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

Do you have any questions? Have to say ah, stuffy in the heart will suppress the bad oneself. Well, if you don't say it, I'll say it. In the example of our access list, there is a new content, component.oncompleted: {}, what is this stuff? And then we'll talk about it.

Signal processor

The signal processor, in fact, is equivalent to the slot in Qt. But we don't see a clearly defined function like C + + ... Yes, that's it, you really only see a pair of curly braces! Yes, this is a block of code in JavaScript. In fact, you can understand that it is an anonymous function. And in JavaScript, the function is actually named block of code. The advantage of a function is that you can call it in other places by name, and the advantage of code block is that no one can invoke it except where it is defined, in a word, it's private. A block of code is a combination of a series of statements that make a sequence of statements execute together.

Let's go back and look at the signal processor, its name is a bit special, generally on{signal} this form. For example, the Button element in Qt Quick has a signal clicked (), so you might want to write a code like this:

Rectangle {    width:320;    height:480;        Button {        id:quit;        Text: "Exit";        Anchors.left:parent.left;        Anchors.leftmargin:4;        Anchors.bottom:parent.bottom;        Anchors.bottommargin:4;        onclicked: {            qt.quit ();}}    }

The QML code above is actually a simple QML application, which puts an exit button in the lower left corner of the window, which triggers the clicked () signal of the button when the user taps it, and we define the signal processor to respond to the clicked () signal-call Qt.quit () to exit the application.

You see, when the signal is clicked (), the signal processor is named onclicked. It is as simple as on start followed by the name of the signal (the first letter capitalized).

Grouping properties

In some cases, a '. ' symbol or grouping symbol is used to form a logical group of related attributes. The grouping attribute can be written like this:

Text {    font.pixelsize:18;    Font.bold:true;}

You can also write this:

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

In fact, it can be understood that the type of the Font property itself is an object, and this object has Pixelsize/bold/italic/underline and so on properties. For property values of type object, you can use the "." operator to expand each member of an object to assign values to it, or you can assign values to the members you want to assign by grouping the symbols (a pair of curly braces). For the latter, the form is the same as the definition of the object, at least it looks different from the wood. So you can understand the example above: The Font object is aggregated within the Text object. OK, that's aggregation.

Attached properties

Property is really hard to do! Not yet finished, not only you bored, I also quickly sit. This is the last point, I promise, but it is also the most complex and incomprehensible attribute. For this kind of thing, I always practice, do not understand the words to accept, you just when it was born so, existence is reasonable, as long as learn how to use it OK.

In the syntax of the QML language, there is the concept of an attached property (attached properties) and an additional signal processor (attached signal handlers), which is an additional property attached to an object. Essentially, these properties are implemented and provided by additional types (attaching type), which may be attached to objects of another type. The difference between an attached property and a normal property is that the normal properties of an object are provided by the object itself or its base class (or ancestors that are traced upward along the inheritance level).

For example, the following Item object uses additional properties and additional signal handlers:

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

You see, the Item object can access and set the values of keys.enabled and keys.onreturnpressed. Enabled is a property of the Keys object. Onreturnpressed is actually a signal to the Keys object. For additional signal processors, it is different from the conventional signal processor mentioned earlier. Ordinary signal processor, you need to know the signal name, and then according to the syntax of on{signal} to define the name of the signal handler, and the additional signal processing, you simply by appending the type name to refer to it, the code block assigned to it.

Finally, the Keys object, which is provided by Qt Quick, is specifically for the Item to handle key event objects. It defines a number of signals for a specific key, such as the onreturnpressed above, and also defines more common onpressed and onreleased signals, which you can typically use to handle keystrokes (please control Qt C + + Keypressevent and Keyreleaseevent to understand). They have a name that is the KeyEvent parameter of the event, which contains the details of the key. If a key is processed, the event.accepted should be set to true to prevent it from being passed on.

Here is an example of using the onpressed signal, which detects the left ARROW key:

Item {    anchors.fill:parent;    Focus:true;    Keys.onpressed: {        if (Event.key = = qt.key_left) {            console.log ("Move Left");            event.accepted = True;}}    }


Well, here's a basic introduction to QML language, and I'm sure you can read the simple QML document now. Some students may have doubts, this section still have some things to see not to speak ah, such as RECTANGLE/TEXT/IMAGE/ITEM/BUTTON/COMPONENT/QT and so on, sorry, now can only carry a confused outfit understand, the next we will talk about this stuff.

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.