【发布时间】:2019-06-21 19:34:01
【问题描述】:
我正在使用 pyqtgraph 中的 BarGraphItem 创建条形图,如果单击/选择了条形图,我想更改条形图的外观,但我不知道如何执行此操作。
条形图显示良好,我可以设置原始颜色,但在任何地方都找不到任何关于如何更改颜色的参考(在我的情况下是为了反映所选状态)
【问题讨论】:
-
我的回答对你有用吗?
标签: python colors bar-chart pyqtgraph
我正在使用 pyqtgraph 中的 BarGraphItem 创建条形图,如果单击/选择了条形图,我想更改条形图的外观,但我不知道如何执行此操作。
条形图显示良好,我可以设置原始颜色,但在任何地方都找不到任何关于如何更改颜色的参考(在我的情况下是为了反映所选状态)
【问题讨论】:
标签: python colors bar-chart pyqtgraph
重载PlotWidget 和BarGraphItem。检查您的PlotWidget.mousePressEvent 的QMouseEvent 位置是否在您的条形之一内:
import pyqtgraph as pg
class MyBarGraphItem(pg.BarGraphItem):
def __init__(self):
super().__init__()
def setAttr(self, **opts):
if 'x' in opts:
self.x = opts['x']
if 'height' in opts:
self.height = opts['height']
if 'width' in opts:
self.width = opts['width']
if 'brushes' in opts:
self.brushes = opts['brushes']
super().setOpts(**opts)
class MyPlot(pg.PlotWidget):
def __init__(self):
super().__init__()
self.bars = None
def mousePressEvent(self, ev):
pos = self.getPlotItem().vb.mapSceneToView(ev.pos())
if self.bars is not None:
for i,_ in enumerate(self.bars.x):
if self.bars.x[i]-self.bars.width/2 < pos.x() < self.bars.x[i]+self.bars.width/2\
and 0 < pos.y() < self.bars.height[i]:
b = self.bars.brushes
b[i] = pg.QtGui.QColor(255,255,255)
self.bars.setAttr(brushes=b)
print('clicked on bar '+str(i))
ev.accept()
super().mousePressEvent(ev)
def addBars(self, bars):
self.bars = bars
self.addItem(bars)
if __name__ == '__main__':
app = pg.mkQApp()
plot = MyPlot()
bars = MyBarGraphItem()
bars.setAttr(brushes=[pg.hsvColor(float(x) / 5) for x in range(5)], x=[i for i in range(5)], height=[1,5,2,4,3], width=0.5)
plot.addBars(bars)
plot.show()
app.exec()
【讨论】: