Skip to content Skip to sidebar Skip to footer

Attach Colors Of My Choosing To Each Slice Of Qpieseries

I want to make each slice of a pie chart a color of my choosing. I need to know the snytax of QPieSlice (if that is what I use) and how to attach a color to a particular slice of t

Solution 1:

When you use the append() method of QPieSeries, passing it the name and value it returns its associated QPieSlice so you must use that element

from PyQt5 import QtCore, QtGui, QtWidgets, QtChart


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    data = {
        "Auto": (10, QtGui.QColor("#00FF00")),
        "Employment": (20, QtGui.QColor("#1A8CFF")),
        "Insurance": (30, QtGui.QColor("salmon")),
        "Household": (40, QtGui.QColor(255, 0, 255)),
        "Housing": (40, QtGui.QColor("blue")),
        "Entertainment": (30, QtGui.QColor(0, 255, 255)),
        "Utilities": (20, QtGui.QColor("#aabbcc")),
        "Other": (10, QtGui.QColor("gray")),
    }

    series = QtChart.QPieSeries()

    for name, (value, color) in data.items():
        _slice = series.append(name, value)
        _slice.setBrush(color)

    chart = QtChart.QChart()
    chart.addSeries(series)
    chart.setTitle("Example for https://stackoverflow.com/questions/56727499")
    chart.legend().setAlignment(QtCore.Qt.AlignBottom)
    chart.legend().setFont(QtGui.QFont("Arial", 7))

    chartview = QtChart.QChartView(chart)
    chartview.setRenderHint(QtGui.QPainter.Antialiasing)

    w = QtWidgets.QMainWindow()
    w.setCentralWidget(chartview)
    w.resize(640, 480)
    w.show()

    sys.exit(app.exec_())

enter image description here


But you can also build a QPieSlice using the name and value you can pass it using the other append() method:

# ...
series = QtChart.QPieSeries()

for name, (value, color) in data.items():
    _slice = QtChart.QPieSlice(name, value)
    _slice.setBrush(color)
    series.append(_slice)

chart = QtChart.QChart()
# ...

And you can also build by creating a list of QPieSlice using the third append() method:

# ...
series = QtChart.QPieSeries()

slices = []

for name, (value, color) in data.items():
    _slice = QtChart.QPieSlice(name, value)
    _slice.setBrush(color)
    slices.append(_slice)

series.append(slices)

chart = QtChart.QChart()
# ...

Update:

In your case, use the second method:

_slice = series.append("Auto", self.expensesWindow.piechart[0])
_slice.setBrush(QColor('#00FF00'))
_slice = series.append("Employment", self.expensesWindow.piechart[1])
_slice.setBrush(QColor('#1A8CFF'))
# ...

Post a Comment for "Attach Colors Of My Choosing To Each Slice Of Qpieseries"