2014-02-21 175 views
2

試圖創建餅圖形狀,但出於某種原因,我無法正確地將它連接在一起。當我運行我的代碼時,它會在彼此之上創建很多段。 這裏是我的代碼:如何在python中使用pyqt創建餅圖

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
import sys, random 


app = QApplication(sys.argv) 
scene = QGraphicsScene() 
families = [1,2,3,4,5,6,7] 
total = 0 
colours = [] 
set_angle = 0 
count1 = 0 
total = sum(families) 
for count in range(len(families)): 
    number = [] 
    for count in range(3): 
     number.append(random.randrange(0, 255)) 
    colours.append(QColor(number[0],number[1],number[2])) 


for family in families:  
    angle = round(family/total*16*360) 
    ellipse = QGraphicsEllipseItem(0,0,400,400) 
    ellipse.setPos(0,0) 
    ellipse.setStartAngle(set_angle) 
    ellipse.setSpanAngle(angle) 
    ellipse.setBrush(colours[count1]) 
    set_angle = angle 
    count1 +=1 
    scene.addItem(ellipse) 
view = QGraphicsView(scene) 
view.show() 
app.exec_() 

回答

1

的問題與integer division,檢查這一行:angle = round(family/total*16*360),它可以是固定設置total = float(sum(families))或把此行from __future__ import division在你的代碼的開始,這兩種解決方案是有效的。

0

爲xndrme說你需要

from __future__ import division 

你不過段仍然會在彼此的頂部,因爲它們都具有相同的起始角度。

set_angle = angle 

應該

set_angle = angle + angle 
2

挖這個線程,因爲它可能幫助別人。 @巴里的答案几乎是正確的,但需要一些調整。

事實上,有一個完美的圓形狀的橢圓,您需要更改行:

set_angle = angle 

set_angle += angle 

這樣,set_angle(這是起始角度我們的「餡餅塊」)始終是畫布上繪製的最後一個角度。

此外,該行:

angle = round(family/total*16*360) 

可以寫成這樣(爲便於閱讀的緣故):

angle = round(float(family*(16*360))/total) 

所以工作的例子會(使用Python3 & PyQt5):

from PyQt5.QtWidgets import QGraphicsScene, QApplication, QGraphicsView, QGraphicsEllipseItem 
from PyQt5.Qt import QColor 
import sys, random 


app = QApplication(sys.argv) 
scene = QGraphicsScene() 

families = [1,2,3,4,5,6,7,8,9,10] 
total = 0 
set_angle = 0 
count1 = 0 
colours = [] 
total = sum(families) 

for count in range(len(families)): 
    number = [] 
    for count in range(3): 
     number.append(random.randrange(0, 255)) 
    colours.append(QColor(number[0],number[1],number[2])) 

for family in families: 
    # Max span is 5760, so we have to calculate corresponding span angle 
    angle = round(float(family*5760)/total) 
    ellipse = QGraphicsEllipseItem(0,0,400,400) 
    ellipse.setPos(0,0) 
    ellipse.setStartAngle(set_angle) 
    ellipse.setSpanAngle(angle) 
    ellipse.setBrush(colours[count1]) 
    set_angle += angle 
    count1 += 1 
    scene.addItem(ellipse) 

view = QGraphicsView(scene) 
view.show() 
app.exec_() 

希望它有幫助。