在 QML 中,可以通过添加 Text 组件来为饼图添加标签。为了按照数据的顺序正确的排列这些标签,可以使用 QML 的 Math 模块中的 pi 常量来计算每个 slice 的中心点和角度,然后设置 Text 的位置和旋转。
下面的代码示例演示了如何为 QML 饼图添加标签:
import QtQuick 2.0 import QtQuick.Controls 2.0 import QtQuick.Shapes 1.0 import QtQuick.Layouts 1.0 import QtMath 1.0
Rectangle { width: 400 height: 400
property var slices: [
{ value: 10, color: "#00BFFF", label: "Slice 1" },
{ value: 20, color: "#00FF7F", label: "Slice 2" },
{ value: 15, color: "#FFD700", label: "Slice 3" },
{ value: 5, color: "#8A2BE2", label: "Slice 4" },
{ value: 25, color: "#DC143C", label: "Slice 5" }
]
property int radius: 150
property int borderWidth: 5
Shape {
id: pieChart
anchors.fill: parent
ShapePath {
strokeWidth: borderWidth
width: parent.width
height: parent.height
fillRule: ShapePath.Stretch
startX: parent.width / 2 + radius
startY: parent.height / 2
for (var i = 0; i < slices.length; i++) {
var slice = slices[i]
var angle = slice.value / slices.reduce(function (acc, s) {
return acc + s.value
}, 0) * 2 * Math.PI
var endX = parent.width / 2 + radius * Math.cos(-Math.PI / 2 + angle + i * angle)
var endY = parent.height / 2 + radius * Math.sin(-Math.PI / 2 + angle + i * angle)
Path