我想使饼图的每个切片成为我选择的颜色。我需要知道QPieSlice的语法(如果这是我使用的),以及如何将颜色附加到馅饼的特定切片上。例如,我希望“自动”切片为“#00FF00”,“就业”切片为“#1A8CFF”,等等。
下面是我的馅饼。我已经尝试过各种方法,例如:
QPieSlice.setBrush(QPieSlice.setColor(QColor('#00FF00')))
但是它不起作用,即使可以,我也不知道如何将其附加到特定切片上以及放置在何处。
series.append("Auto", self.expensesWindow.piechart[0])
series.append("Employment", self.expensesWindow.piechart[1])
series.append("Insurance", self.expensesWindow.piechart[2])
series.append("Household", self.expensesWindow.piechart[3])
series.append("Housing", self.expensesWindow.piechart[4])
series.append("Entertainment", self.expensesWindow.piechart[5])
series.append("Utilities", self.expensesWindow.piechart[6])
series.append("Other", self.expensesWindow.piechart[7])
答案 0 :(得分:2)
在使用append()
的QPieSeries
方法时,为其传递名称和值会返回其关联的QPieSlice
,因此必须使用该元素
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_())
但是您也可以使用名称和值来构建QPieSlice
,也可以使用其他append()方法来传递它:
# ...
series = QtChart.QPieSeries()
for name, (value, color) in data.items():
_slice = QtChart.QPieSlice(name, value)
_slice.setBrush(color)
series.append(_slice)
chart = QtChart.QChart()
# ...
您还可以使用第三个QPieSlice
方法通过创建append()
的列表进行构建:
# ...
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()
# ...
更新:
根据您的情况,使用第二种方法:
_slice = series.append("Auto", self.expensesWindow.piechart[0])
_slice.setBrush(QColor('#00FF00'))
_slice = series.append("Employment", self.expensesWindow.piechart[1])
_slice.setBrush(QColor('#1A8CFF'))
# ...