Qt Quick Mouse event handling, keyboard, timer

Source: Internet
Author: User
Tags case statement

In the "signals and slots of the Qt Quick event Processing", we describe how to use the built-in types of signals in QML and how to define the signals themselves, this time we look at how to deal with the mouse, keyboard, timer and other events. These times are usually completed by signals when they are processed.

Mouse Event Handling

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

Color-Changing Rectangle Demo sample

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";}}    }

Use the Qmlscene handle_mouse.qml command to see the effect of the execution. The above code, however, draws a rectangle that changes the color of the rectangular area when the left mouse button is pressed, and exits the app when the right mouse button is pressed.

Figure 1 is the effect of the first execution:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzm9ydw9r/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/southeast "/>

Figure 1 handle_mouse.qml initial execution effect

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


Figure 2 Effect of left mouse button click

Let's say you click the right mouse button. The program will exit.

The demo sample is rudimentary. But enough to explain how to handle mouse events, let's take a slow look.

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 agent of the item it attaches to.

Mousearea has a lot of properties, enabled is used to control whether mouse events are handled, the default value is true, assuming you set to False, then the item it proxies ignores mouse events. The Acceptedbuttons property sets the event that receives the thousand mouse button (left, right, middle) to demonstrate the 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 attribute. You can use it to describe an effective mouse area. The Demo sample Code "Anchors.fill:parent;" indicates that the entire rectangular region accepts mouse events.

Mousearea also has a lot of other properties, such as hoverenabled, pressed, and so on. Please refer to the QT Help documentation.

Demonstrates the sample code. The onclicked and ondoubleclicked two signal handlers were used within the Mousearea object, and they mousearea onclicked and ondoubleclicked signals accordingly. Mousearea also has a lot of other signals. such as Onpressed/onreleased/onentered/onexited/onpressandhold and so on, from the name can see the meaning of these signals.

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 you can see in the Demo sample code, the MouseEvent button property holds the mouse pointer position that was pressed, X, and Y properties. Another important attribute, accepted, is to set its value to true if you do not want the event to pass down again after handling the mouse event.

The ondoubleclicked signal represents a double-click event, and its reference is also MouseEvent type, and in the demo sample, the mouse is double-clicked and the rectangle color becomes gray.

Simple mouse event handling for these things. Depending on the needs of your application, you may also handle signals such as onpressed/onreleased/onentered and so on. Please refer to Qt help.

Keyboard event Handling

You may be less likely to handle keyboard events on your phone (with one exception, Back button), but you can't avoid the keyboard on your computer.

A moving text instance

Look at the Demo 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 demo example moves a text string by four buttons up or down. The SPACEBAR selects the check box and the ESC key exits the app.

Figure 3 is the initial execution:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzm9ydw9r/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/southeast "/>

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 explanation demonstrates the sample code. Describes how to handle key events using the Keys object and the signal processor

Keys and Signal Processors

In fact, in the "QT Quick event processing signals and slots", "QT Quick simple Tutorial" and "QML Language Foundation" three articles we have mentioned the Keys object, and some examples have been used in the demonstration, here, we specifically introduced, and strive to make everyone on keys and key processing has a more comprehensive The understanding.

The Keys object is provided by Qt Quick. An object specifically for Item handling of key events.

It defines a very large number of signals for specific keys, such as onreturnpressed/onescapepressed/ondownpressed/ondigit0pressed/onbackpressed and so on, and it also defines a more general OnP Ressed and onreleased signals, in general. You can use both signals to handle most keystrokes (please compare keypressevent and keyreleaseevent in Qt C + +). They have a name that is the KeyEvent parameter of the event. Includes specific information about the keystrokes.

KeyEvent represents a keystroke event. Assuming 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 within a list. Suppose an object receives a key, and the object behind it does not receive the key event. Demo Sample 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, assuming it consumes a key. The LIKEQT will not be received. You can change the keys.onpressed additional signal processor for the Text object. Add Qt.key_space to the case list to see the effect.

The Priority property agrees that you set the precedence of the Keys attached property. There are two ways to handle keystrokes before the item, which is the default behavior after the item is processed.

You can compare the Qt C + + keypressevent () function to understand that 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 logical relationship during this period is also very easy. If keys processes the key first, as it eats a key. The Item object to which it is attached 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 demo sample, 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, let's say you want to change the key-response logic for it. This is already mentioned when explaining the priority attribute.

Finally, the other point is to explain. Suppose you want an element to handle the button, you need to focus on it, which is controlled by the Item's Focus property, which is set to true.

Now let's explain the demo sample code.

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, using the Switch-case statement to sort the key attribute of the event parameter. Let's say you change the position of Text by four keys up or down. Reset accepted to True. Declare that these keys have been taken by the Lord to find a home, or return directly. Give others the opportunity to handle the keys. As you can see, it is because of this. CheckBox talent get the SPACEBAR to select or cancel the check box.

When the CheckBox object definition in the sample is shown, there is no special handling of the key, as the implementation of Qt Quick has already processed the key.

Well, it seems like very little content? Walk on. Watch the timer go.

Timer

Does the function of the timer still have to say? It seems a bit wordy. A timer is an event that is triggered periodically, almost the same as an alarm clock that is often used. You can use the timer to complete some recurring tasks, such as checking the connection with the server to stay dead. For example, backing up user data ...

Timer Object Introduction

In QML, the timer represents the timer. It is also very easy 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, the default is one-time (as if it is not the same as Qtimer). The running property. Set the timer to true to start working. Set to False to break the dish. The default is False. The Triggeredonstart property. How to say, Qt is always so good to us all kind of embarrassed, this attribute is to take into account the special needs of some comrades. The timer starts to wait for a set interval before triggering, assuming that you set this property to True, 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 look at a simple demo sample. Countdown.

Countdown Program

World Cup countdown by day, the mountain in the world thousand years, we this demo sample with 1 seconds to top it one day, countdown 10 seconds. Then we'll open the champagne and 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. It to devolve a button. 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, and the ID is attrs. The value of the Counter property is initialized to 10 in the additional signal processor component.oncompleted. In the Timer object, the Ontriggered signal processor decrements counter, and when counter changes the text of the text object to 0 o'clock, it is "clap now!".

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:

Watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzm9ydw9r/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/dissolve/70 /gravity/southeast "/>

Figure 6 Timing

Figure 7 is the end of the countdown effect:


Figure 7 Countdown End

Suppose you use Qmlscene to execute a COUNTDOWN.QML document, you may find that it has a BUG oh, the "Start" button can be counted as a normal countdown for the first click. The next time will not be ... I've found the problem, but I'll leave it to you.

Think back. Restudying

    • A brief introduction to Qt quick
    • QML Language Basics
    • Qt Quick's Hello World Text detail explanation
    • Qt Quick Simple Tutorial
    • Qt Quick event signal and slot management


Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Qt Quick Mouse event handling, keyboard, timer

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.