最近的软件需求做一个画线测量工具,发现QML只有Map的测距工具,无奈自己动手实现。
话不多说,先上图给大家看看。
非常简单的代码,但是看不到有人分享,难道大家都藏着吗?所以分享出来给大家参考,有需求的话自己再添加吧。下面上代码。
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property real clickNum
property real startX
property real startY
property real stopX
property real stopY
Canvas{
id : canvas
anchors.fill: parent
onPaint: {
var ctx = getContext("2d")
ctx.lineWidth = 5
ctx.strokeStyle = "black";//轮廓颜色
ctx.fillStyle = "black";//填充颜色
ctx.beginPath()
ctx.clearRect(0,0,canvas.width,canvas.height)
ctx.stroke()
ctx.beginPath()
ctx.moveTo(startX,startY)
ctx.lineTo(stopX,stopY)
ctx.stroke()
}
MouseArea{
id:area;
anchors.fill: parent;
acceptedButtons: Qt.LeftButton | Qt.RightButton
hoverEnabled: true
onClicked: {
if(mouse.button === Qt.LeftButton)
{
if(clickNum === 0)
{
startX = mouseX
startY = mouseY
clickNum++;
}
else{
stopX = mouseX
stopY = mouseY
clickNum = 0
canvas.requestPaint()
}
}
}
onPositionChanged: {
if(clickNum === 1)
{
stopX = mouseX
stopY = mouseY
canvas.requestPaint()
}
}
}
}
}