PyQt5中QChart柱状图如何设置颜色
时间: 2023-09-28 08:06:01 浏览: 439
在PyQt5中,可以通过设置QBarSet对象的颜色来设置柱状图的颜色。具体步骤如下:
1. 创建QBarSet对象并设置值
```
barset = QBarSet("Bar 1")
barset.append([1, 2, 3, 4, 5])
```
2. 创建QBarSeries对象并将QBarSet添加到其中
```
barseries = QBarSeries()
barseries.append(barset)
```
3. 创建QChart对象并将QBarSeries添加到其中
```
chart = QChart()
chart.addSeries(barseries)
```
4. 创建QChartView对象并将QChart设置为其图表
```
chartview = QChartView(chart)
chartview.setRenderHint(QPainter.Antialiasing)
```
5. 设置QBarSet的颜色
```
barset.setColor(QColor("#1E90FF"))
```
其中,setColor()方法接受一个QColor对象作为参数,可以使用十六进制颜色码或预定义颜色名称,例如"#1E90FF"表示深天蓝色。
完整代码示例:
```
from PyQt5.QtChart import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
app = QApplication([])
window = QMainWindow()
barset = QBarSet("Bar 1")
barset.append([1, 2, 3, 4, 5])
barset.setColor(QColor("#1E90FF"))
barseries = QBarSeries()
barseries.append(barset)
chart = QChart()
chart.addSeries(barseries)
chart.setTitle("Bar Chart")
chart.setAnimationOptions(QChart.SeriesAnimations)
axis = QBarCategoryAxis()
axis.append(["A", "B", "C", "D", "E"])
chart.createDefaultAxes()
chart.setAxisX(axis, barseries)
chartview = QChartView(chart)
chartview.setRenderHint(QPainter.Antialiasing)
window.setCentralWidget(chartview)
window.show()
app.exec_()
```
阅读全文