Raf*_*SCS 6 geometry qt draw sector qml
我知道可以使用以下代码在QML中绘制一个圆圈:
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
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:如果我需要画一个圆圈的扇区怎么办?(披萨切片)并使这些切片中的每一个都可点击?我可以只使用QML吗?
nea*_*gab 14
使用qml绘制它,您不需要画布。作为指导方针,我通常在决定实现之前先浏览 Qt 的示例。下面的代码可以在“形状”示例中找到。
import QtQuick 2.11
import QtQuick.Shapes 1.15
Shape {
width: 120
height: 130
anchors.bottom: parent.bottom
anchors.right: parent.right
// multisample, decide based on your scene settings
layer.enabled: true
layer.samples: 4
ShapePath {
fillColor: "black"
strokeColor: "darkBlue"
strokeWidth: 20
capStyle: ShapePath.FlatCap
PathAngleArc {
centerX: 65; centerY: 95
radiusX: 45; radiusY: 45
startAngle: -180
sweepAngle: 180
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,使用Canvas(和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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我实际上从这个答案中获取了代码,因为Qt的Canvas实现了HTML5 Canvas API.这使得在网络上找到示例变得非常容易; 例如,只搜索"draw pie slice blah html5 canvas".
对于鼠标检测,你将不得不刷掉你的数学技能......
......或者只是从这里窃取代码.:)
请注意,Canvas仅在调整大小时重新绘制,或者在调用requestPaint()时重新绘制,因此如果要根据鼠标位置更改切片的颜色,则需要调用该函数以查看颜色更改.