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