在QML中绘制弧/圆扇形? [英] Draw an arc/circle sector in QML?
问题描述
我知道可以使用以下代码在QML中绘制一个圆:
I know that it is possible to draw a circle in QML using the following code:
Rectangle {
width: 150
height: 150
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
color: "#095e7b"
border.color: "#0a2f4a"
border.width: 2
radius: width*0.5
}
我的问题是:如果我需要画一个圆的扇区怎么办? (比萨饼切片)并使每个切片都可点击?我只能使用QML做到这一点吗?
My question is: what if I need to draw a sector of a circle. (Pizza Slices) and make each of these slices clickable? Can I do this using QML only?
推荐答案
Yes, using Canvas (and Context2D):
import QtQuick 2.3
Rectangle {
width: 400
height: 400
Canvas {
anchors.fill: parent
onPaint: {
var ctx = getContext("2d");
ctx.reset();
var centreX = width / 2;
var centreY = height / 2;
ctx.beginPath();
ctx.fillStyle = "black";
ctx.moveTo(centreX, centreY);
ctx.arc(centreX, centreY, width / 4, 0, Math.PI * 0.5, false);
ctx.lineTo(centreX, centreY);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "red";
ctx.moveTo(centreX, centreY);
ctx.arc(centreX, centreY, width / 4, Math.PI * 0.5, Math.PI * 2, false);
ctx.lineTo(centreX, centreY);
ctx.fill();
}
}
}
我实际上是从此代码获得的答案,因为Qt的Canvas实现了HTML5 Canvas API.这使得在网上查找示例变得非常容易.例如,只需搜索绘制饼图等等html5 canvas".
I actually took the code for this from this answer, as Qt's Canvas implements the HTML5 Canvas API. This makes it really easy to find examples on the web; just search for "draw pie slice blah html5 canvas", for example.
要进行鼠标检测,您必须精通数学技能...
For the mouse detection, you'll have to brush off your maths skills...
...或只是从此处窃取代码>. :)
... or just steal the code from here. :)
Note that Canvas only repaints when it's resized, or when requestPaint() is called, so if you want to change the colour of a slice depending on the mouse position, you'll need to call that function to see the colour change.
这篇关于在QML中绘制弧/圆扇形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!