Qt on Android: simple Qt Quick tutorial

Source: Internet
Author: User

In the previous article "Qt on Android: Qt Quick Hello World graphic explanation", we have run the first Qt Quick example-HelloQtQuickApp on the computer and Android mobile phones respectively. What about this article, we will introduce some basic concepts of Qt Quick programming to lay the foundation for creating complex Qt Quick applications.

All rights reserved foruok, If You Need To reprint please indicate from blog http://blog.csdn.net/foruok.

First, let's take a look at the main. qml file in "Hello World, Qt on Android: Qt Quick:


Now we will use the main. qml file to explain.

Import Statement

The first line of code of the main. qml file is import QtQuick 2.0. This line of code introduces the QtQuick module. The import Statement is similar to # include in C ++ and has the same effect as import in Java. It's no longer long.

Basic elements of Qt Quick

As a standard library of QML, Qt Quick provides many basic elements and controls to help us build Qt Quick applications. Compared with C ++, QML is equivalent to C ++, while Qt Quick is equivalent to STL. Well, you may think it's okay to be confused.

Rectangle

The third line of main. qml Code defines a Rectangle object as the root object of the QML document. The description of the object in the qml file is explained in the article Qt on Android: QML language basics. Let's see what Rectangle is.

Rectangle is used to draw a filled Rectangle. It can contain borders, solid colors, gradient colors, or even borders ......

Rectangle has many attributes.

Width is used to specify the width, and height is used to specify the height. We have already seen it.

The color attribute can specify the fill color, while the gradient attribute is used to set gradient for filling. If you specify both color and gradient, gradient takes effect. If you set the color attribute to transparent, then you can achieve the effect of drawing only the border without filling.

Border. width specifies the border width and border. color specifies the border color.

Rectangle can also draw rounded Rectangle. You only need to set the radius attribute.

Here is a simple example:

Rectangle {    width: 320;    height: 480;    color: "blue";    border.color: "#808080";    border.width: 2;    radius: 12;}


You can modify the main. qml file of HelloQtQuickApp to view the effect, or create a new project.

The above Rectangle object, we

Color

For color values, you can use color names in QML, such as blue/red/green/transparent, or "# RRGGBB" or "# AARRGGBB, you can also use Qt. rgba ()/Qt. lighter () and so on. For more information, see the "QML Basic Type: color" page in the Qt SDK.

The color type has four attributes: r, g, B, and a, which respectively represent the red, green, blue, and alpha components of a color value. You can use them like this:

Text {    color: "red"    // prints "1 0 0 1"    Component.onCompleted: console.log(color.r, color.g, color.b, color.a)}

The Gradient type in the Gradient QML is Gradient. The Gradient is determined by two or more color values. QML will automatically perform interpolation between the specified colors for seamless filling. Gradient uses GradientStop to specify a color value and its position (the value is between 0.0 and 1.0 ).

Well, there is no code, so let's take a look at an example:

Rectangle {    width: 100;     height: 100;    gradient: Gradient {        GradientStop { position: 0.0; color: "#202020"; }        GradientStop { position: 0.33; color: "blue"; }        GradientStop { position: 1.0; color: "#FFFFFF"; }    }}

Gradient can only be used to create a vertical Gradient, but in other directions, it can be achieved by specifying the rotation attribute for Rectangle. The following is an example:

Rectangle {    width: 100;     height: 100;    rotation: 90;    gradient: Gradient {        GradientStop { position: 0.0; color: "#202020"; }        GradientStop { position: 1.0; color: "#A0A0A0"; }    }}

We just used the rotation attribute. In fact, it comes from the Rectangle parent class Item.

Item

Item is the base class of all visual elements in Qt Quick. Although it does not draw anything on its own, it defines most of the common attributes required to draw elements, such as x, y, width, height, anchoring, And button processing.

There are many attributes of items. In addition to the attributes mentioned above, there are also scale/smooth/anchors/antialiasing/enabled/visible/state/states/children. For more information, see the Qt help documentation.

You can use Item to group other visual elements. For example:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Item {        id: gradientGroup;        Rectangle {            x: 20;            y: 20;            width: 120;            height: 120;            gradient: Gradient {                GradientStop { position: 0.0; color: "#202020"; }                GradientStop { position: 1.0; color: "#A0A0A0"; }            }        }        Rectangle {            x: 160;            y: 20;            width: 120;            height: 120;            rotation: 90;            gradient: Gradient {                GradientStop { position: 0.0; color: "#202020"; }                GradientStop { position: 1.0; color: "#A0A0A0"; }            }        }    }    Component.onCompleted: {        console.log("visible children: " ,gradientGroup.visibleChildren.length);        console.log("visible children: " ,gradientGroup.children.length);        for(var i = 0; i < gradientGroup.children.length; i++){            console.log("child " , i, " x = ", gradientGroup.children[i].x);        }    }}

After grouping, you can access the child element through the children or visibleChildren attribute of Item, as shown in the code above.

In addition, you may have noticed that the interface layout of the Qt Quick application can be completed by combining the four attributes x, y, width, and height. However, this layout uses absolute coordinates, it is not easy to adapt to a variety of mobile device resolutions. If you read ", you may notice the anchors attribute that appears many times in the sample code. Its Item attribute is a new layout method introduced by Qt Quick.

Use anchors for interface Layout

Anchors provides a way to determine the position of an element on the interface by specifying the relationship between an element and other elements.

You can imagine that each item has seven invisible anchors: left, horizontalCenter, top, and bottom) right, verticalCenter, and baseline ). You can see:


In, there is no baseline, and the baseline is used to locate the text. You can imagine a line of text sitting baseline. For elements without text, baseline and top are consistent.

When anchors is used for layout, in addition to alignment of the anchors, you can also white the four edges of the specified top (topMargin), bottom (bottomMargin), left (leftMargin), and right (rightMargin. You can see the following figure:


Now, the basic knowledge has been introduced. You can look at some examples.

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Rectangle {        id: rect1;        anchors.left: parent.left;        anchors.leftMargin: 20;        anchors.top: parent.top;        anchors.topMargin: 20;        width: 120;        height: 120;        gradient: Gradient {            GradientStop { position: 0.0; color: "#202020"; }            GradientStop { position: 1.0; color: "#A0A0A0"; }        }    }    Rectangle {        anchors.left: rect1.right;        anchors.leftMargin: 20;        anchors.top: rect1.top;        width: 120;        height: 120;        rotation: 90;        gradient: Gradient {            GradientStop { position: 0.0; color: "#202020"; }            GradientStop { position: 1.0; color: "#A0A0A0"; }        }    }}

The code above works the same as the sample code (absolute coordinate layout) that used the Item grouping before. The left side of the second rectangle starts from the right side of the first rectangle, and the top is aligned to the top of the first rectangle. The reference to the first rectangle is completed by the id attribute. For more information, see Qt on Android: QML language basics.

In addition to the anchors attributes described above, there are also some attributes. For example, centerIn indicates placing one Item in the center of another item; fill indicates filling a certain item ...... For more information, see the document of the Item class. Here is an example of using centerIn and fill:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Rectangle {        color: "blue";        anchors.fill: parent;        border.width: 6;        border.color: "#888888";        Rectangle {            anchors.centerIn: parent;            width: 120;            height: 120;            radius: 8;            border.width: 2;            border.color: "black";            antialiasing: true;            color: "red";        }    }}

Z-order and transparency

In addition to the x and y attributes, Item also has a z attribute to specify the Z order of elements in the scenario. The type of the z attribute is real. The smaller the value, the lower the base of the element (away from us). The larger the value, the closer the element to us.

The opacity attribute of Item can specify the transparency of an element. The value ranges from 0.0 to 1.0.

Combining the Z-order and transparency can sometimes achieve good results. The following is a simple example:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Rectangle {        x: 20;        y: 20;        width: 150;        height: 100;        color: "#606080";        z: 0.5;    }    Rectangle {        width: 100;        height: 100;        anchors.centerIn: parent;        color: "#a0c080";        z: 1;        opacity: 0.6;    }}

In addition to visual effects, we sometimes need to arrange the Z sequence of elements in the scenario. For example, an image browser may display a loading icon when loading an image. This icon must be displayed on top of the image. In this case, you can set the Z sequence of the loading element to be greater than the Z sequence of the image element.

Button Processing

As mentioned above, items can process cases. All elements inherited from items can process keys, such as Rectangle and Button. This is mentioned in the document "Qt on Android: QML language basics.

Item handles Keys by attaching the attribute Keys. The Keys object is provided by Qt Quick for the Item to process key events. It defines many signals for specific buttons, such as onReturnPressed and 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.

Here is a simple example. When the Escape and Back keys are detected, the app exits. When the number keys are detected, the corresponding numbers are displayed through Text. The Code is as follows:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    color: "#c0c0c0";    focus: true;    Keys.enabled: true;    Keys.onEscapePressed: Qt.quit();    Keys.onBackPressed: Qt.quit();    Keys.onPressed: {        switch(event.key){        case Qt.Key_0:        case Qt.Key_1:        case Qt.Key_2:        case Qt.Key_3:        case Qt.Key_4:        case Qt.Key_5:        case Qt.Key_6:        case Qt.Key_7:        case Qt.Key_8:        case Qt.Key_9:            keyView.text = event.key - Qt.Key_0;            break;        }    }    Text {        id: keyView;        font.bold: true;        font.pixelSize: 24;        text: qsTr("text");        anchors.centerIn: parent;    }}

In this example, three additional signal processors, onPressed, onEscapePressed, and onBackPressed, are used. The onPressed signal parameter is event and contains the key information, the program uses the switch statement to compare with the enumerated values of the Qt object to filter the keys we are interested in.


Item has many attributes, so we will not demonstrate them one by one. Please refer to Qt for more information.

You must have noticed that the above example uses the Text object. Next we will introduce it.

Text

The Text element can display plain Text or rich Text (Text modified using HTML tags ). It has font/text/color/elide/textFormat/wrapMode/horizontalAlignment/verticalignment and other attributes. You can use these attributes to determine how the Text element displays the text.

When the textFormat attribute is not specified, the Text element uses Text by default. autoText, which automatically detects whether the text is plain or rich. If you explicitly know that the text to be displayed is rich, you can explicitly specify the textFormat attribute.

The following is a simple example to show the blue problem. The line is broken at the word boundary:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Text {        width: 150;        height: 100;        wrapMode: Text.WordWrap;        font.bold: true;        font.pixelSize: 24;        font.underline: true;        text: "Hello Blue Text";        anchors.centerIn: parent;        color: "blue";    }}

The following example only displays the Text in blue:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Text {        width: 150;        height: 100;        wrapMode: Text.WordWrap;        font.bold: true;        font.pixelSize: 24;        font.underline: true;        text: "Hello Blue Text";        anchors.centerIn: parent;    }}

The style attribute of the Text element provides several types of Text styles, including Text. Outline, Text. Raised, and Text. Sunken. The styleColor attribute can be used with the style (if no style is specified, styleColor does not take effect). For example, if the style is Text. Outline, styleColor is the color of the Text contour. Let's look at a simple example:

import QtQuick 2.0Rectangle {    width: 300;    height: 200;    Text {        id: normal;        anchors.left: parent.left;        anchors.leftMargin: 20;        anchors.top: parent.top;        anchors.topMargin: 20;        font.pointSize: 24;        text: "Normal Text";    }    Text {        id: raised;        anchors.left: normal.left;        anchors.top: normal.bottom;        anchors.topMargin: 4;        font.pointSize: 24;        text: "Raised Text";        style: Text.Raised;        styleColor: "#AAAAAA" ;    }    Text {        id: outline;        anchors.left: normal.left;        anchors.top: raised.bottom;        anchors.topMargin: 4;        font.pointSize: 24;        text: "Outline Text";        style: Text.Outline;        styleColor: "red";    }    Text {        anchors.left: normal.left;        anchors.top: outline.bottom;        anchors.topMargin: 4;        font.pointSize: 24;        text: "Sunken Text";        style: Text.Sunken;        styleColor: "#A00000";    }}

In addition to Text elements, anchors is used to complete the interface layout.

Text is introduced here. Let's look at the Button.

Button

Buttons may be the most commonly used controls in GUI applications. The buttons in QML are similar to QPushButton. clicking a Button triggers a clicked () signal. In QML documents, you can specify a signal processor for clicked () to respond to user operations.

To use a Button, import QtQuick. Controls 1.1 must be introduced.

Let's take a look at a simple example and click the button to exit the application. The Code is as follows:

import QtQuick 2.0import QtQuick.Controls 1.1Rectangle {    width: 300;    height: 200;    Button {        anchors.centerIn: parent;        text: "Quit";        onClicked: Qt.quit();    }}

You can run it to see the effect.

Now let's take a look at the attributes of the Button.

Text attribute specifies the button text.

The checkable attribute sets whether the Button is optional. If the Button option is checked, the selected status of the Button is saved. In fact, I have never used this attribute ......

The iconName attribute specifies the name of an icon. If a resource corresponding to this name exists in the icon topic of the platform, the Button can be loaded and displayed. IconSource specifies the icon location through URL. The iconName attribute has a higher priority than iconSource.

The isDefault attribute specifies whether the button is the default button. If it is the default button, you press Enter to trigger the clicked () signal of the button.

The pressed status of the button is saved in the pressed attribute.

Menu attribute, allowing you to set a menu for the button (a small drop-down arrow may appear in the button), the menu will pop up when you click the button. The default value is null.

Action attribute. You can set the action of a button. action can define attributes such as checked, text, and tooltip. The default value is null.

ActiveFocusOnPress: Specifies whether to obtain the focus when the user presses the button. The default value is false.

The style attribute is used to customize the style of a button. It is associated with a ButtonStyle class that allows you to customize the background of the button.

In fact, the Button is relatively simple and easy to use. I don't want to worry about it anymore. Let's take a look at the style and end the introduction of the Button.

ButtonStyle

To use ButtonStyle, You need to introduce QtQuick. Controls. Styles 1.1.

The ButtonStyle class has three attributes: background, control, and label. We can override background to customize a button. The control property points to the button object of the application ButtonStyle. You can use it to access various states of the button. The label attribute indicates the text of a button. You can replace it if it is not pleasing to the eye.

Background is actually a Component object. Let's look back at the concept of Component. Here we simply use Rectangle to customize the button background. See the following example:

import QtQuick 2.0import QtQuick.Controls 1.1import QtQuick.Controls.Styles 1.1Rectangle {    width: 300;    height: 200;    Button {        text: "Quit";        anchors.centerIn: parent;        style: ButtonStyle {            background: Rectangle {                implicitWidth: 70;                implicitHeight: 25;                border.width: control.pressed ? 2 : 1;                border.color: (control.hovered || control.pressed) ? "green" : "#888888";            }        }    }}

I specify a ButtonStyle object for the style object to customize the style of the Button. This locally implemented ButtonStyle object overrides the background attribute and defines the button background through the Rectangle object. I have defined the suggested width and height of the background, and set the Border width of the background rectangle according to the pressed attribute of the button (control is a reference of the actual button, the border color varies with the hovered and pressed attributes of the button.

The final result is as follows: when the mouse is hovering over the button, the border color is green; when the mouse is pressed, the border turns thick and the color is green.

For ButtonStyle, if multiple buttons are used at the same time, the above method is a little complicated and can be used as follows:

import QtQuick 2.0import QtQuick.Controls 1.1import QtQuick.Controls.Styles 1.1Rectangle {    width: 300;    height: 200;    Component{        id: btnStyle;        ButtonStyle {            background: Rectangle {                implicitWidth: 70;                implicitHeight: 25;                color: "#DDDDDD";                border.width: control.pressed ? 2 : 1;                border.color: (control.hovered || control.pressed) ? "green" : "#888888";            }        }    }    Button {        id: openButton;        text: "Open";        anchors.left: parent.left;        anchors.leftMargin: 10;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 10;        style: btnStyle;    }    Button {        text: "Quit";        anchors.left: openButton.right;        anchors.leftMargin: 6;        anchors.bottom: openButton.bottom;        style: btnStyle;    }}

This time, we defined a component and set its id attribute value to btnStyle. btnStyle is used directly when the style attribute is set in the Button.

Well, ButtonStyle will be introduced here. Next we will introduce Image.

Image

An Image can be displayed as long as it is supported by Qt, such as JPG, PNG, BMP, GIF, and SVG. It can only display static images. For GIF and other formats, only the first frame is displayed. If you want to display animations, you can use AnimateSprite or AnimateImage.

The width and height attributes of the Image are used to set the size of the elements. If you do not set them, the Image uses the size of the Image itself. If you set the width and height, the image may be stretched to fit the size. In this case, the fillMode attribute can set the filling mode of the Image. It supports Image. stretch (Stretch), Image. preserveAspectFit (proportional scaling), Image. preserveAspectCrop (proportional scaling, maximized filling of the Image, cropping the Image if necessary), Image. tile (tiled horizontally and vertically, just like tiled), Image. tileVertically (vertical tile), Image. tileHorizontally (horizontal tile), Image. pad (keep the image unchanged) and other modes.

By default, the Image will load the Image in a blocking manner. If the Image to be displayed is small, there is no problem. If the resolution is very high, it will be troublesome. In this case, you can set the asynchronous attribute to true to enable the asynchronous loading mode. In this mode, the Image uses a thread to load the Image, you can display a wait icon or other things on the interface to tell users that it will take a while. Then, when the value of status (enumeration value) is Image. Ready, the loading wait interface is hidden.

What is more powerful is that Image supports loading images from the network. Its source attribute type is url, which can accept any network protocol supported by Qt, such as http and ftp. When the Image identifies that the source you provide is a network resource, the asynchronous loading mode is automatically enabled. In this case, the progress SS (value range: 0.0 to 1.0) of the Image and status (enumeration value) are updated in a timely manner. You can determine when your loading wait prompt page ends based on these values.

Come here first and see how to use it. The following is the simplest example:

import QtQuick 2.0Image {    source: "images/yourimage.png"}

Replace source with an existing image path to see the effect.

Show Network Image

The following is a slightly more complex example, showing images on the network. A circled Loading icon is displayed before downloading and Loading. After the image is loaded successfully, the Loading icon is hidden. If an error occurs during Loading, A simple error message is displayed. Check the Code:

import QtQuick 2.0import QtQuick.Controls 1.1Rectangle {    width: 480;    height: 320;    color: "#121212";    BusyIndicator {        id: busy;        running: true;        anchors.centerIn: parent;        z: 2;    }    Label {        id: stateLabel;        visible: false;        anchors.centerIn: parent;        z: 3;    }    Image {        id: imageViewer;        asynchronous: true;        cache: false;        anchors.fill: parent;        fillMode: Image.PreserveAspectFit;        onStatusChanged: {            if (imageViewer.status === Image.Loading) {                busy.running = true;                stateLabel.visible = false;            }            else if(imageViewer.status === Image.Ready){                busy.running = false;            }            else if(imageViewer.status === Image.Error){                busy.running = false;                stateLabel.visible = true;                stateLabel.text = "ERROR";            }        }    }    Component.onCompleted: {        imageViewer.source = "http://image.cuncunle.com/Images/EditorImages/2013/01/01/19/20130001194920468.JPG";    }}

Image resources are searched from the Internet and used only for demonstration programs. If you have any copyright concerns, Please prompt me to modify them.

Image object. The asynchronous attribute is set to true. However, for network resources, Image is asynchronously loaded by default. This attribute does not work. You only need to set it when you want to asynchronously load local resources. The cache attribute is set to false, indicating that the Image does not need to be cached. I have set the proportional scaling mode for the fillMode attribute.

OnStatusChanged is a signal processor. When the status attribute of an Image changes, a statusChanged () signal is sent. When we introduced the Signal processor in Qt on Android: QML language basics, we knew that the Signal processor followed the on {Signal} syntax, so the name here is onStatusChanged. In the code block of the signal processor, I access its status attribute through the id of the Image object and update the interface according to different States.

You may wonder that the statusChanged signal is not explicitly mentioned in the Image class reference manual in Qt help. In fact, there are still a lot of signals that are not mentioned in the Qt document. What should I do? Find the SDK header file. For example, the Image header file is Qt5.2.0 \ 5.2.0 \ mingw48_32 \ include \ QtQuick \ 5.2.0 \ QtQuick \ private \ qquickimage_p.h, read this header file and you will see the QQuickImage class in Qt C ++ corresponding to the Image in QML. The parent class of QQuickImage is QQuickImageBase, the class declaration of QQuickImageBase can be found in the file Qt5.2.0 \ 5.2.0 \ mingw48_32 \ include \ QtQuick \ 5.2.0 \ QtQuick \ private \ qquickimagebase_p.h. Find the actual status attribute and check the following code:

Q_PROPERTY(Status status READ status NOTIFY statusChanged)
The Q_PROPERTY macro is used to define the attributes of the QObject and Its Derived classes, so that the defined attributes can be accessed in QML. The preceding statement defines the read-only status attribute and specifies that the statusChanged signal is sent when the attribute changes. K.O .!

Now let's take a look at running the program. (I have stolen a lazy one, but they all directly modify the main. qml file of the HelloQtQuickApp to see the effects of various examples ). Is the loading process:



I set the fill color of the Rectangle object as the root element of the QML document to "#121212", so the background is close to black. Is the effect of image loading:

Examples/examples + QnVzeUluZGljYXRvcjwvaDI + PHA + examples/Uyr7Su7j2tci0/examples + examples/examples + annotations + watermarks = "brush: java; "> BusyIndicator {id: busy; running: true; anchors. centerIn: parent; z: 2 ;}
Although BusyIndicator only has two attributes: running and style, its ancestors have many attributes. The anchors and z used above are all attributes inherited from Item and can be directly used.


Well, at the first stage, I can say goodbye to the simple tutorial.

All rights reserved foruok, If You Need To reprint please indicate from blog http://blog.csdn.net/foruok.

Review the previous articles:

Qt on Android: Qt Quick introduction Qt on Android: QML language basics Qt on Android: Qt Quick Hello World graphic explanation if you have the patience to see here, I think you can certainly complete some complicated Qt Quick applications based on the content you have already introduced. Congratulations!

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.