Qml 和外部js文件协同工作
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow
可以用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 219
r1.mapFromItem(r2, mouse.x, mouse.y) 意思是将
r2坐标系的鼠标位置转换成r1坐标系的位置。
还有mapToItem,刚好相反,是将r1坐标系下的鼠标位置转换到r2的坐标系***意不要看反了。
http://doc-snapshot.qt-project.org/qdoc/qml-qtquick-item.html#mapToItem-method-2
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow