Qml and external js Files Work collaboratively

Source: Internet
Author: User

You can use the import as statement to introduce an external js file to the qml file. The following defines a qml file with only one Item.

import QtQuick 2.0import "handler.js" as HandlerItem {    id: top_item    width: 380    height: 200    MouseArea {         anchors.fill: parent        onPressed: Handler.onPressed(mouse);    }}

Take a look at the handler. js file:

function onPressed(mouse) {    console.log(mouse.x, mouse.y);}

When you click the mouse, the console prints the cursor position.


To make it more complex, place the Item of qml in another Rectangle, and then convert the coordinates:

import QtQuick 2.0import "handler.js" as HandlerRectangle {    id: r1    width: 400    height: 400    Item {        id: i1        anchors.fill: parent.fill        Rectangle {            id: r2            width: 200            height: 200            color: "red"            anchors.left: parent.left            anchors.leftMargin: 100            anchors.top: parent.top            anchors.topMargin: 100            MouseArea {                anchors.fill: parent                onPressed: Handler.onPressed(mouse);            }        }    }}

Handler. js file:

function onPressed(mouse) {    console.log("postion in r2 Rectangle");    console.log(mouse.x, mouse.y);    console.log("postion in r1 Rectangle");    var pos = r1.mapFromItem(r2, mouse.x, mouse.y);    console.log(pos.x, pos.y);}

Run:

 ~/Qt5.2.0/5.2.0/gcc_64/bin/qmlscene ./test1.qml


After you click the red area, the console outputs:

postion in r2 Rectangle114 119postion in r1 Rectangle214 219

R1.mapFromItem (r2, mouse. x, mouse. y) indicates

The mouse position of the r2 coordinate system is converted to the r1 coordinate system.


There is also mapToItem. On the contrary, it is to convert the mouse position in the r1 coordinate system to the r2 coordinate system. Be careful not to look at the reverse.

Http://doc-snapshot.qt-project.org/qdoc/qml-qtquick-item.html#mapToItem-method-2


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.