本文由我司收集整编,推荐下载,如有疑问,请与我司联系
Qml
和外部
js
文件协同工作
2014/01/15
0
可以用
import
as
语句将外部
js
文件引入到
qml
文件中,下面定
义了一个
qml
文件,里面只有一个
Item.
import QtQuick 2.0import handler.js as HandlerItem { id: top_item width: 380 height:
200 MouseArea {
anchors.fill: parent onPressed: Handler.onPressed(mouse); }}
看一下
handler.js
文件:
function onPressed(mouse) { console.log(mouse.x, mouse.y);}
当鼠标单击的时候,控
制台将打印光标的位置。
再复杂一点,让
qml
的
Item
在另一个
Rectangle
里面
,
然后转换坐标位置:
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
文件:
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);}
运行一下:
~/Qt5.2.0/5.2.0/gcc_64/bin/qmlscene ./test1.qml
鼠标点击红色区域后,控制台输出:
postion
in
r2
Rectangle114
119postion
in
r1
Rectangle214
219r1.mapFromItem(r2,
mouse.x, mouse.y)
意思是将
r2
坐标系的鼠标位置转换成
r1
坐标系的位置。
还有
mapToItem
,刚好相反,是将
r1
坐标系下的鼠标位置转换到
r2
的坐标系
下,注意不要看反了。
doc-snapshot.qt-project/qdoc/qml-qtquick-item.html#mapToItem-method-2
tips:
感谢大家的阅读,本文由我司收集整编。仅供参阅!