5

我是 Python 和 pyqtgraph 的新手。我正在研究不同类型信号的查看器。当前,当我想在鼠标位置中包含十字准线和文本标签时,我被卡住了。我正在使用 GridLayout,因为后来该图与其他几个元素结合在一起。

我试图调整 pyqtgraph 示例 Crosshair / mouse interaction 但除了 pyqtgraph 中的许多其他内容之外,我在 mousemoved() 之前不理解vb = signalgraph.vb的含义,并且脚本引发了 NameError

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

#QtGui.QApplication.setGraphicsSystem('raster')
app = QtGui.QApplication([])
mainwindow = QtGui.QMainWindow()
mainwindow.setWindowTitle('pyqtgraph example: PlotWidget')
mainwindow.resize(1000,800)
cw = QtGui.QWidget()
mainwindow.setCentralWidget(cw)

gridlayout = QtGui.QGridLayout()
cw.setLayout(gridlayout)

# define plot windows
signalgraph = pg.PlotWidget(name='Signalgraph')

# set position and size of plot windows
gridlayout.addWidget(signalgraph,0,0)

mainwindow.show()


# sample data
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,0,0,8,8,8,9,9,9,0,0]

# plot 1
curve = pg.PlotCurveItem(x,y[:-1],pen='w',stepMode=True)
signalgraph.addItem(curve)

#cross hair in signalgraph
vLine = pg.InfiniteLine(angle=90, movable=False)
hLine = pg.InfiniteLine(angle=0, movable=False)
signalgraph.addItem(vLine, ignoreBounds=True)
signalgraph.addItem(hLine, ignoreBounds=True)

# Here I am not sure what to do ...
vb = signalgraph.vb
##vb = pg.ViewBox()


def mouseMoved(evt):
    pos = evt[0]
    if signalgraph.sceneBoundingRect().contains(pos):
        mousePoint = vb.mapSceneToView(pos)
        index = int(mousePoint.x())
        if index > 0 and index < len(x):
            label.setText("<span style='font-size: 12pt'>x=%0.1f, <span style='color: red'>y1=%0.1f</span>" % (mousePoint.x(), y[index], data2[index]))
        vLine.setPos(mousePoint.x())
        hLine.setPos(mousePoint.y())


proxy = pg.SignalProxy(signalgraph.scene().sigMouseMoved, rateLimit=60, slot=mouseMoved)
signalgraph.scene().sigMouseMoved.connect(mouseMoved)


# Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

非常感谢迈克尔

4

1 回答 1

8

“vb”是 PlotItem 类的一个属性。由于signalgraph它是一个 PlotWidget,您可能不会期望它具有相同的属性(尽管它确实包装了其内部 PlotItem 中的一些方法)。所以你需要的代码是:

vb = signalgraph.plotItem.vb

如果您对 PlotWidget 和 PlotItem 之间的区别感到困惑,请阅读 QGraphicsView 和 QGraphicsItem 类(均在 Qt 文档中)。PlotWidget 只不过是一个 QGraphicsView,里面显示了一个 PlotItem。

于 2013-07-22T16:03:09.573 回答