2014-09-25 222 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 } 
} 
}