Qt on ANDROID:QT Quick event handling mouse, keyboard, timer

Source: Internet
Author: User
Tags case statement

In the "Qt on ANDROID:QT Quick event processing signal and slot" described in QML how to use the built-in type of signal and how to customize the signal, this time we look at how to deal with the mouse, keyboard, timer and other events. These times are usually done with signals when they are processed.

Advertise: I am participating in the CSDN blog contest, please give me the entry "Qt on ANDROID:QT Quick event processing signals and slots " vote, thank you.

Mouse Event Handling

Desktop development, it is unavoidable to deal with mouse events ...

Color-Changing Rectangle example

Look at a simple example of handling 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";}}    }

Using the Qmlscene handle_mouse.qml command, you can see the effect of running. The above code simply draws a rectangle, which changes the color of the rectangle when the left mouse button is pressed, and exits the app when the right mouse button is pressed. Figure 1 is the effect of a fresh run:


Figure 1 Handle_mouse.qml initial run effect

Figure 2 is the effect after clicking the left mouse button:


Figure 2 Effect of left mouse button click

If you click the right mouse button, the program will exit.

The example is rudimentary, but enough to illustrate how to handle mouse events, let's take a look at it.

Mousearea

The Mousearea object can be attached to an item to handle the mouse event, which itself is an invisible item. Within it, you can directly reference the properties and methods of the object it attaches to. You can understand Mousearea as the proxy for the item it is attached to.

Mousearea has many properties, enabled is used to control whether mouse events are handled, the default value is True, and if you set it to False, the item it proxies ignores mouse events. The Acceptedbuttons property sets the event that receives the thousand mouse button (left, right, middle), sample code "AcceptedButtons:Qt.LeftButton | Qt.rightbutton; "indicates that the left and right mouse buttons are processed.

As an item, Mousearea also has the anchors property, which you can use to describe the active mouse area. The sample code "Anchors.fill:parent;" indicates that the entire rectangular region accepts mouse events.

Mousearea also has many other properties, such as hoverenabled, pressed, etc., please refer to the QT Help documentation.

In the sample code, the onclicked and ondoubleclicked two signal handlers are used within the Mousearea object, and they correspond to the onclicked and ondoubleclicked signals of Mousearea, Mousearea and Many other signals, such as onpressed/onreleased/onentered/onexited/onpressandhold and so on, can be seen in the name of these signals.

The parameter of the onclicked signal is the MouseEvent type, named mouse, so you can use mouse directly in the signal processor to query the details of the mouse event. For example, which button is pressed, as seen in the sample code, the button property of the MouseEvent holds the mouse button tag, x, and Y properties that are pressed to save the mouse pointer position. There is also a more important attribute accepted, if you do not want this event to be passed down after you handle the mouse event, set its value to true.

The ondoubleclicked signal represents a double-click event whose parameters are also MouseEvent types, with the mouse double-clicked in the example and the rectangle color dimmed.

Simple mouse Event processing on these, depending on your application needs, you may also handle onpressed/onreleased/onentered and so on, please refer to Qt help.

Keyboard event Handling

On the phone you may be less likely to handle keyboard events (with one exception, Back button), but you will inevitably have to respond to the keyboard on your computer.

A moving text instance

Look at the sample code first, 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; }}

This example moves a text string by the left and right four keys, the SPACEBAR selects the check box, and the ESC key exits the app. Figure 3 is the initial run:


Figure 3 Handle_key Initial effect

Figure 4 is I pressed a few times the arrow keys, press the space bar after the effect:


Figure 4 Moving text, selecting the check box

The following explains the sample code that describes how to use the keys object and the signal processor to handle key events

Keys and Signal Processors

In fact, in the "Qt on ANDROID:QT quick event processing signal and slot", "Qt on ANDROID:QT Quick Simple tutorial" and "Qt on ANDROID:QML Language Foundation" three articles we have mentioned the Keys object, and some examples also Used to, here, we specifically introduced, and strive to make everyone on keys and key processing has a more comprehensive understanding.

The Keys object is an object provided by Qt Quick, specifically for Item handling of key events. It defines a number of signals for specific keys, such as onreturnpressed/onescapepressed/ondownpressed/ondigit0pressed/onbackpressed, and so on, and it also defines a more general onPr Essed and onreleased signals, in general, you can use these two signals to handle most keys (please understand the keypressevent and keyreleaseevent in Qt C + +), they have a name of event KeyEvent Parameter that contains the details of the key.

KeyEvent represents a keystroke event, and if a key is processed, the event.accepted should be set to true to prevent it from being passed on, and if you do not set it, it may continue to be passed on to other item, with some weird problems.

Keys has three properties.

The Enabled property controls whether keys are processed.

The Forwardto property is a list type that represents a pass-through key event to an object in the list, and if an object is received with a key, the object behind it will not receive the key event. Example code "KEYS.FORWARDTO: [MoveText, LIKEQT];" indicates that the forward key is to a Text object with ID movetext and a CheckBox object with an ID of LIKEQT. MoveText in front, if it consumes a key, LIKEQT will not receive it. You can modify the Text object's keys.onpressed additional signal processor and add qt.key_space to the case list to see the effect.

The Priority property allows you to set the precedence of the keys attached property in two ways, before the item handles the key, which is the default behavior and handles the keystrokes after the item. You can understand the keypressevent () function of Qt C + +, if you overload the Keypressevent () method in a derived class, you can call the parent class's keypressevent () at the beginning of the overloaded method, You can also call the parent class's keypressevent () after you have finished processing the event of interest. The logic of this period is also very simple, if the keys handle the key first, if it eats a key, it is attached to the Item object will not receive the button, and vice versa.

Some of the elements provided by Qt Quick itself handle keystrokes, such as the CheckBox in the example, which responds to the SPACEBAR to check or uncheck. And we don't need to attach the keys object to it to handle the keystroke event again. Of course, if you want to change its key-response logic, you can do so, as explained in the priority attribute.

The last thing to note is that if you want an element to handle the button, you need to focus on it, which is controlled by the focus property of Item, which is set to true.

Now let's explain the sample code again.

Rectangle object of the additional signal processor keys.onescapepressed call Qt.quit () exit, small white very, not said.

The Text object implements the Keys.onpressed additional signal processor and uses the Switch-case statement to sort the key property of the event parameter. If it is up and down four keys, change the position of the Text, set accepted to true, declaring that the keys have been taken to find a home, otherwise directly return, give others the opportunity to handle the key. As you can see, it's because of this that the checkbox gets the spacebar to select or cancel the check box.

The CheckBox object definition in the example does not specifically handle keystrokes because the implementation of the Qt Quick provides that the keys have been processed.

Well, it seems like little content. Go on, watch the timer go.

Timer

Does the function of the timer still have to say? It seems a bit wordy. Timer, is a cyclical trigger event, peace is commonly used in the same alarm clock. You can use the timer to do some periodic tasks, such as checking the connection with the server is dead, such as backing up user data ...

Timer Object Introduction

In QML, the timer represents the timer and is simple to use, responding to its ontriggered () signal, and it is a useful signal. In addition, it has several properties to illustrate, interval specify the timing period, the unit is milliseconds, the default value is 1000 milliseconds, repeat set the timer is a periodic trigger or a one-time trigger, default is one-time (as if and Qtimer not the same); Running property, set to True the timer starts to work, set to False for the rest of the dish, the default is false; Triggeredonstart property, how to say, Qt is always so good to us a little bit of that. Sorry, this attribute is to take into account the special needs of some comrades, The timer starts to wait for the set interval to be triggered, if you set this property to True, then the timer starts executing immediately first, the default value is False.

Timer and start ()/Stop ()/restart () Three methods can be called, they will affect the running property, words too literally bar you.

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

Countdown Program

World Cup countdown by day, the mountain in the world thousand years, we this example with 1 seconds to top it one day, countdown 10 seconds, and then open the champagne to celebrate.

See 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 underneath it. A Timer object is defined within the Rectangle object and is not started by default. The timer is activated when the user taps the "Start" button. I also set the Triggeredonstart property of the timer, the period is 1 seconds.

The count is saved in the Qtobject object, the ID is attrs, and the value of the Counter property is initialized in an additional signal processor component.oncompleted of 10. While the timer object's ontriggered signal processor decrements counter, the text of the text object is changed to "Clap now!" when counter is 0 o'clock.

Here, it's so simple.

Look at the effect. Figure 5 is the initial effect:


Figure 5 Countdown Program Initial effect

Figure 6 is the timing effect:


Figure 6 Timing

Figure 7 is the end of the countdown effect:


Figure 7 Countdown End

If you use Qmlscene to run the COUNTDOWN.QML document, you may find it has a BUG oh, "Start" button The first click can be normal countdown, finished next time not ... I've found the problem, but I'll leave it to you.


I am participating in the CSDN blog contest, please give me the entry "Qt on ANDROID:QT Quick event processing signals and slots " vote, thank you.

Look Back, restudying:

    • Qt on ANDROID:QT Quick Introduction
    • Qt on ANDROID:QML Language basics
    • Qt on ANDROID:QT Quick's Hello World text
    • Qt on ANDROID:QT Quick Simple tutorial
    • The signal and slot of Qt on ANDROID: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.