如何在 PyQtChart 中双击获取饼图切片的值

How to Get Value of Pie Slice on double Click in PyQtChart

我想在点击圆环图的切片时获取饼图切片的值。我们怎样才能实现它?我想将 slice 的值存储在一个变量中。请让我知道您的想法或建议。

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_())

您必须使用 doubleClicked signal of the QPieSeries that sends the pressed QPieSlice,并且您可以从该 QPieSeries 中提取所需的信息:

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)

        <b>series.doubleClicked.connect(self.handle_double_clicked)

    def handle_double_clicked(self, slice):
        print(slice.label(), slice.value())</b>