2014-09-25 219 views
3

我知道这是可能使用下面的代码绘制在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 
} 

我的问题是:如果我需要画一个圆的部门。 (比萨切片),并使每个片可点击?我可以只使用QML来做到这一点吗?

回答

8

是,使用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(); 
     } 
    } 
} 

我居然把这个代码从this答案,因为Qt的帆布实现HTML5的Canvas API。这使得在网络上很容易找到示例;例如,只需搜索“绘制饼图切片html5画布”。

对于鼠标的检测,你必须刷过你的数学技能...

...或只是从here窃取代码。 :)

请注意,Canvas仅在调整大小时或在调用requestPaint()时重绘,因此如果要根据鼠标位置更改切片的颜色,则需要调用该函数以查看颜色更改。

3

使用图表http://doc.qt.io/QtCharts/qtcharts-qmlmodule.html

import QtQuick 2.0 
import QtCharts 2.0 

ChartView { 
width: 400 
height: 300 
theme: ChartView.ChartThemeBrownSand 
antialiasing: true 

PieSeries { 
    id: pieSeries 
    PieSlice { label: "eaten"; value: 94.9 } 
    PieSlice { label: "not yet eaten"; value: 5.1 } 
} 
}