问题描述
我正在使用pyqtgraph示例中的十字线示例。单击某个点上的绘图图时,我试图获取一个点的坐标。
在代码中标记为import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui,QtCore
#generate layout
app = QtGui.QApplication([])
win = pg.GraphicslayoutWidget(show=True)
win.setwindowTitle('pyqtgraph example: crosshair')
label = pg.LabelItem(justify='right')
win.addItem(label)
p1 = win.addplot(row=1,col=0)
#pg.dbg()
p1.setAutoVisible(y=True)
#create numpy arrays
#make the numbers large to show that the xrange shows data from 10000 to all the way 0
data1 = 10000 + 15000 * pg.gaussianFilter(np.random.random(size=10000),10) + 3000 * np.random.random(size=10000)
data2 = 15000 + 15000 * pg.gaussianFilter(np.random.random(size=10000),10) + 3000 * np.random.random(size=10000)
p1.plot(data1,pen="r")
p1.plot(data2,pen="g")
vb = p1.vb
def mouseMoved(evt):
pos = evt[0] ## using signal proxy turns original arguments into a tuple
mousePoint = vb.mapScenetoView(pos) <<<<<<<<<<<<<<
print(mousePoint.x(),mousePoint.y())
proxy = pg.SignalProxy(p1.scene().sigMouseClicked,slot=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_()
解决方法
我用另一种方法修改了代码。现在可以正常工作了。
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui,QtCore
#generate layout
app = QtGui.QApplication([])
win = pg.GraphicsLayoutWidget(show=True)
win.setWindowTitle('pyqtgraph example: crosshair')
label = pg.LabelItem(justify='right')
win.addItem(label)
p1 = win.addPlot(row=1,col=0)
#pg.dbg()
p1.setAutoVisible(y=True)
#create numpy arrays
#make the numbers large to show that the xrange shows data from 10000 to all the way 0
data1 = 10000 + 15000 * pg.gaussianFilter(np.random.random(size=10000),10) + 3000 * np.random.random(size=10000)
data2 = 15000 + 15000 * pg.gaussianFilter(np.random.random(size=10000),10) + 3000 * np.random.random(size=10000)
p1.plot(data1,pen="r")
p1.plot(data2,pen="g")
vb = p1.vb
def onClick(event):
items = p1.scene().items(event.scenePos())
mousePoint = vb.mapSceneToView(event._scenePos)
print(mousePoint.x(),mousePoint.y())
if p1.sceneBoundingRect().contains(event._scenePos):
mousePoint = vb.mapSceneToView(event._scenePos)
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]))
p1.scene().sigMouseClicked.connect(onClick)
## 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_()```