Pyqtgraph中的十字准线类
我想定义一个叫做 Crosshair 的类,这个类可以附加到 pyqtgraph 的图表上。我在示例中找到了以下代码片段:
#cross hair
vLine = pg.InfiniteLine(angle=90, movable=False)
hLine = pg.InfiniteLine(angle=0, movable=False)
p1.addItem(vLine, ignoreBounds=True)
p1.addItem(hLine, ignoreBounds=True)
vb = p1.vb
def mouseMoved(evt):
pos = evt[0] ## using signal proxy turns original arguments into a tuple
if p1.sceneBoundingRect().contains(pos):
mousePoint = vb.mapSceneToView(pos)
index = int(mousePoint.x())
if index > 0 and index < len(data1):
label.setText("<span style='font-size: 12pt'>x=%0.1f, <span style='color: red'>y1=%0.1f</span>, <span style='color: green'>y2=%0.1f</span>" % (mousePoint.x(), data1[index], data2[index]))
vLine.setPos(mousePoint.x())
hLine.setPos(mousePoint.y())
proxy = pg.SignalProxy(p1.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)
我开始把它改成一个类,像这样:
class CrossHair():
def __init__(self, p1):
self.vLine = pg.InfiniteLine(angle=90, movable=False)
self.hLine = pg.InfiniteLine(angle=0, movable=False)
self.p1 = p1
self.vb = self.p1.vb
p1.addItem(self.vLine, ignoreBounds=True)
p1.addItem(self.hLine, ignoreBounds=True)
self.proxy = pg.SignalProxy(self.p1.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
def mouseMoved(self, evt):
pos = evt[0] ## using signal proxy turns original arguments into a tuple
if self.p1.sceneBoundingRect().contains(pos):
mousePoint = self.vb.mapSceneToView(pos)
index = int(mousePoint.x())
# if index > 0 and index < len(data1):
# label.setText("<span style='font-size: 12pt'>x=%0.1f, <span style='color: red'>y1=%0.1f</span>, <span style='color: green'>y2=%0.1f</span>" % (mousePoint.x(), data1[index], data2[index]))
self.vLine.setPos(mousePoint.x())
self.hLine.setPos(mousePoint.y())
ch = CrossHair(p1)
这样做对吗?换句话说,我这样做是正确的吗?我想把图表附加到十字准星上,但我不太确定该怎么做,也不知道这样做是否合适。
另外,我该如何从图表中获取数据值(注释部分)呢?
1 个回答
2
更好的做法是创建一个pg.GraphicsObject的子类,这个子类里面包含两个无限线作为子元素。参考资料有:QtGui.QGraphicsItem和pg.GraphicsItem,另外还有customGraphicsItem的例子可以看看。
这个类应该有一个setPos()的方法,用来设置十字准星的起始位置。然后,你可以添加一些应用层的代码来跟踪鼠标的位置,并相应地更新十字准星,就像在十字准星的例子中那样。或者,你也可以让十字准星自己自动跟踪鼠标的位置。
关于第二个问题:你至少需要告诉CrossHair它应该查询哪些PlotDataItem或PlotCurveItem,以确定与垂直线相交的y坐标。