Qt on Android: Mouse, keyboard, and timer for handling Qt Quick events

Source: Internet
Author: User

In Qt on Android: signals and slots for Qt Quick event processing, this article describes how to use built-in signals in QML and how to customize signals, this time, let's take a look at how to handle mouse, keyboard, timer, and other events. These processing times are usually completed through signals.

I'm participating in the CSDN blog contest. please vote for my article Qt on Android: signals and slots for Qt Quick event processing. Thank you.

Mouse event processing

For desktop development, it is inevitable to handle mouse events ......

Color-changing rectangle example

Let's look at a simple example of processing mouse events. first look at the code (handle_mouse.qml ):

import QtQuick 2.0import QtQuick.Controls 1.1Rectangle {    width: 320;    height: 240;        MouseArea {        anchors.fill: parent;        acceptedButtons: Qt.LeftButton | Qt.RightButton;        onClicked: {            if(mouse.button == Qt.RightButton){                Qt.quit();            }            else if(mouse.button == Qt.LeftButton){                color = Qt.rgba((mouse.x % 255) / 255.0 , (mouse.y % 255) / 255.0, 0.6, 1.0);            }        }        onDoubleClicked: {            color = "gray";        }    }}

Run the "qmlscene handle_mouse.qml" command to view the running effect. The code above is just to draw a rectangle. When the left mouse button is pressed, the color of the rectangle area is changed, and the right mouse button is clicked to exit the application. Figure 1 shows the effect of the running:


Figure 1 Initial running result of handle_mouse.qml

Figure 2 shows the effect of clicking the left mouse button:


Figure 2 Effect of clicking the left mouse button

If you right click, the program will exit.

The example is simple, but it is enough to explain how to handle mouse events. Let's take a look at it.

MouseArea

The MouseArea object can be appended to an item for the item to process mouse events. It is an invisible item. Inside the object, you can directly reference the attributes and methods of the object to which it is attached. You can understand MouseArea as the proxy of the item it attaches.

MouseArea has many attributes. enabled is used to control whether to process mouse events. The default value is true. If you set it to false, the items it represents will ignore the mouse events. The acceptedButtons attribute is used to set the events (left-click, right-click, and Middle-click) generated by holding mouse keys. The example code "acceptedButtons: Qt. leftButton | Qt. rightButton; "indicates the left mouse button and right mouse button.

As an item, MouseArea also has the anchors attribute. You can use it to describe a valid mouse area. The sample code "anchors. fill: parent;" indicates that mouse events are accepted throughout the rectangle.

MouseArea has many other attributes, such as hoverEnabled and pressed. For more information, see the Qt help documentation.

In the sample code, two signal processors onClicked and onDoubleClicked are used in the MouseArea object. They correspond to the onClicked and onDoubleClicked signals of the MouseArea, and many other signals exist in the MouseArea, for example, onPressed/onReleased/onEntered/onExited/onPressAndHold. The meaning of these signals can be seen from the name.

The parameter of the onClicked signal is of the MouseEvent type and is named "mouse". Therefore, you can use "mouse" in the signal processor to query the details of the mouse event. For example, if a button is pressed, as shown in the sample code, the button attribute of the MouseEvent stores the mouse key marked by the pressed button, and the x and y attributes Save the mouse pointer position. Another important attribute, accepted, is set to true if you do not want this event to be passed down after processing the mouse event.

The onDoubleClicked signal indicates a double-click event. Its parameter is also of the MouseEvent type. In this example, double-click the mouse and the rectangle turns gray.

Simple mouse event processing is about this content. Based on your application's needs, you may also handle onPressed, onReleased, onEntered, and other signals. For more information, see Qt help.

Handle Keyboard Events

On your mobile phone, you may be dealing with less Keyboard Events (with one exception, the BACK button), but on your computer, you have to respond to the keyboard.

Active text instance

First look at the sample code, handle_key.qml:

import QtQuick 2.0import QtQuick.Controls 1.1Rectangle {    width: 320;    height: 480;    color: "gray";        focus: true;    Keys.enabled: true;    Keys.onEscapePressed: {        Qt.quit();    }    Keys.forwardTo: [moveText, likeQt];        Text {        id: moveText;        x: 20;        y: 20;        width: 200;        height: 30;        text: "Moving Text";        color: "blue";        //focus: true;        font { bold: true; pixelSize: 24;}        Keys.enabled: true;        Keys.onPressed: {            switch(event.key){            case Qt.Key_Left:                x -= 10;                break;            case Qt.Key_Right:                x += 10;                break;            case Qt.Key_Down:                y += 10;                break;            case Qt.Key_Up:                y -= 10;                break;            default:                return;            }            event.accepted = true;        }    }        CheckBox {        id: likeQt;        text: "Like Qt Quick";        anchors.left: parent.left;        anchors.leftMargin: 10;        anchors.bottom: parent.bottom;        anchors.bottomMargin: 10;        z: 1;    }}

In this example, you can move a text string by pressing the upper, lower, and left buttons. The space key selects the check box and the Esc key exits. Figure 3 is the initial operation:


Figure 3 initial handle_key Effect

Figure 4 shows the effect after I press the arrow key several times and press the Space key:


Figure 4 move text and select the check box

The following example explains how to use the Keys object and signal processor to process key events.

Keys and Signal Processor

In fact, in Qt on Android: Qt Quick event processing signals and slots, Qt on Android: Qt Quick simple tutorial, and Qt on Android: we have mentioned the Keys object in the three articles of QML language basics, which are also used in some examples. Here, we will introduce it specifically, we strive to give you a comprehensive understanding of Keys and key processing.

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, onEscapePressed, onDownPressed, onDigit0Pressed, and onBackPressed. It also defines more common onPressed and onReleased signals, you can use these two signals to process most of the buttons (refer to keyPressEvent and keyReleaseEvent in Qt C ++). They have a KeyEvent parameter named event, contains detailed information about the buttons.

KeyEvent indicates a key event. If a key is processed, the event. accepted should be set to true to prevent it from being passed. If you do not set it, it may be passed to other items, and some strange problems may occur.

Keys has three attributes.

The enabled attribute controls whether buttons are processed.

The forwardTo attribute is a list type. It indicates that a key event is passed to an object in the list. If an object accept a key, the object after the key column will not receive the key event. The sample code "Keys. forwardTo: [moveText, likeQt];" indicates that the forwarding key is used to send the Text object whose id is moveText and the CheckBox object whose id is likeQt. MoveText is in front. If it consumes a key, likeQt cannot receive it. You can modify the Keys. onPressed additional signal processor of the Text object, and add Qt. Key_Space to the case list to see the effect.

The priority attribute allows you to set the priority of the additional attributes of Keys. There are two types: buttons are processed before the Item, which is the default action and Keys are processed after the Item. You can understand the keyPressEvent () function of Qt C ++. If you overload the keyPressEvent () method in the derived class, you can call the keyPressEvent () of the parent class at the beginning of the overload method, or call the keyPressEvent () of the parent class after you have processed the events of interest (). The logical relationship during this period is also very simple. If Keys processes Keys first, if it eats a key, the Item object to which it is attached won't receive the Keys, and vice versa.

Some elements provided by Qt Quick process the buttons themselves, such as the CheckBox in the example. It responds to the Space key to select or cancel the selection. However, we do not need to attach a Keys object to it to process key events again. Of course, if you want to change its key response logic, you can do so. This is already mentioned when interpreting the priority attribute.

The last thing to note is that if you want to process a key for an element, you need to focus on it. This is controlled by the focus attribute of the Item and set it to true.

Now let's explain the sample code.

The append signal processor Keys. onEscapePressed of the Rectangle object calls Qt. quit () to exit.

The Text object implements the Keys. onPressed additional signal processor. It uses the switch-case statement to sort the key attribute of the event parameter. If it is up, down, left, and right keys, change the location of the Text, set accepted to true, declare that these keys have been named by the master to find the destination; otherwise, return directly and give others the opportunity to process the buttons. As you can see, it is in this way that CheckBox can get the Space key to select or cancel the check box.

In the example, when the CheckBox object is defined, no buttons are specially processed, because the implementation provided by Qt Quick has processed the buttons.

Well, it seems that there is very little content? Go and watch the timer.

Timer

Do I need to talk about the role of the timer? It seems awkward. A timer is an event triggered periodically. It is similar to a commonly used alarm clock. You can use the timer to complete some periodic tasks, such as checking the connection with the server, or backing up user data ......

Timer object Introduction

In QML, Timer represents a Timer and is easy to use. It responds to its onTriggered () signal, which is also a useful signal. In addition, there are several attributes to describe. interval specifies the scheduled period, in milliseconds. The default value is 1000 milliseconds. repeat sets whether the timer is triggered periodically or once, the default value is one-time (as if it is different from QTimer). The running attribute is set to true, and the timer starts to work. If it is set to false, the default value is false. The triggeredOnStart attribute is used. How can this problem be solved, qt is always a little embarrassed for us so well. This attribute takes into account the special needs of some comrades. After the timer is started, it will wait for the set interval to trigger, if you set this attribute to true, the timer is triggered immediately when execution starts. The default value is false.

Timer also has three methods, namely start (), stop (), and restart (), which can affect the running attribute.

Now let's look at a simple example, countdown.

Countdown Program

The countdown to the World Cup is calculated by day. In this example, we use one second to top the world, and the last ten seconds. Then we open the champagne to celebrate.

Check the code (count_down.qml ):

import QtQuick 2.0import QtQuick.Controls 1.1Rectangle {    width: 320;    height: 240;    color: "gray";    QtObject{        id: attrs;        property int counter;        Component.onCompleted:{            attrs.counter = 10;        }    }        Text {        id: countShow;        anchors.centerIn: parent;        color: "blue";        font.pixelSize: 40;    }        Timer {        id: countDown;        interval: 1000;        repeat: true;        triggeredOnStart: true;        onTriggered:{            countShow.text = attrs.counter;            attrs.counter -= 1;            if(attrs.counter < 0)            {                countDown.stop();                countShow.text = "Clap Now!";            }        }    }        Button {        id: startButton;        anchors.top: countShow.bottom;        anchors.topMargin: 20;        anchors.horizontalCenter: countShow.horizontalCenter;        text: "Start";        onClicked: {            countDown.start();        }    }}

I put a Text object on the interface and put a button below it. A Timer object is defined in the Rectangle object, which is disabled by default. Start the timer when you click "Start. I also set the triggeredOnStart attribute of the timer. The cycle is 1 second.

The count is saved in the QtObject object. The id is attrs, and the counter attribute value is initialized to 10 in the additional signal processor Component. onCompleted. In the onTriggered signal processor of the Timer object, the counter is decreased. When the counter is 0, the Text of the Text object is changed to "Clap Now! ".

That's simple.

Let's see the effect. Figure 5 shows the initial effect:


Figure 5 initial effect of the Countdown Program

Figure 6 shows the timing effect:


Figure 6 Timing

Figure 7 shows the effect of the Countdown:


Figure 7 countdown ends

If you use qmlscene to run the countdown. qml document, you may find that it has a BUG. The "Start" button can be counted down for the first time, but it won't work until next time ...... I have found the problem, but leave it for you to solve it.


I am participating in the CSDN blog contest. please vote for my article Qt on Android: signals and slots for Qt Quick event processing. Thank you.

Let's take a look at it:

  • Qt on Android: Qt Quick introduction
  • Qt on Android: Basic QML Language
  • Qt on Android: Hello World for Qt Quick
  • Qt on Android: simple Qt Quick tutorial
  • Qt on Android: signals and slots of Qt Quick event processing


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.