I want to get the value of pie slice when I click on the slice of the donut chart. How can we achieve it ? I want to store the value of slice in an variable. Please let me know your thoughts or suggestions.
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from PyQt5.QtGui import QPainter, QPen, QFont
from PyQt5.QtCore import Qt
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("DonutChart Example")
self.setGeometry(100,100, 400,600)
self.create_donutchart()
def create_donutchart(self):
series = QPieSeries()
series.setHoleSize(0.35)
series.append("Protein 4.2%", 4.2)
slice = QPieSlice()
slice = series.append("Fat 15.6%", 15.6)
slice.setExploded()
slice.setLabelVisible()
series.append("Other 23.8%", 23.8);
series.append("Carbs 56.4%", 56.4);
chart = QChart()
chart.legend().hide()
chart.addSeries(series)
chart.setAnimationOptions(QChart.SeriesAnimations)
chart.setTitle("DonutChart Example")
chart.setTheme(QChart.ChartThemeBlueCerulean)
chartview = QChartView(chart)
chartview.setRenderHint(QPainter.Antialiasing)
self.setCentralWidget(chartview)
App = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec_())
You have to use the doubleClicked
signal of the QPieSeries
that sends the pressed QPieSlice
, and from that QPieSeries you can extract the required information:
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("DonutChart Example")
self.setGeometry(100,100, 400,600)
self.create_donutchart()
def create_donutchart(self):
series = QPieSeries()
series.setHoleSize(0.35)
series.append("Protein 4.2%", 4.2)
slice = series.append("Fat 15.6%", 15.6)
slice.setExploded()
slice.setLabelVisible()
series.append("Other 23.8%", 23.8);
series.append("Carbs 56.4%", 56.4);
chart = QChart()
chart.legend().hide()
chart.addSeries(series)
chart.setAnimationOptions(QChart.SeriesAnimations)
chart.setTitle("DonutChart Example")
chart.setTheme(QChart.ChartThemeBlueCerulean)
chartview = QChartView(chart)
chartview.setRenderHint(QPainter.Antialiasing)
self.setCentralWidget(chartview)
series.doubleClicked.connect(self.handle_double_clicked)
def handle_double_clicked(self, slice):
print(slice.label(), slice.value())