在PyQtGraph中返回鼠标光标坐标

时间:2016-02-20 19:47:57

标签: python plot pyqt pyqtgraph

我是PyQtGraph的新手,想要用它来快速可视化我的数据采集。以前我使用的是matplotlib,重绘图形是我的瓶颈。在转换到PyQtGraph之后,我目前只缺少matplotlib的一个功能。即,返回鼠标光标的x和y坐标。

如何在使用PyQtGraph绘制的图中调用/模仿鼠标光标的x坐标和y坐标的返回?

修改! - 在实现leongold的提示后,代码能够返回鼠标位置而不会失去速度。代码如下:

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

def gaussian(A, B, x):
  return A * numpy.exp(-(x/(2. * B))**2.)

def mouseMoved(evt):
  mousePoint = p.vb.mapSceneToView(evt[0])
  label.setText("<span style='font-size: 14pt; color: white'> x = %0.2f, <span style='color: white'> y = %0.2f</span>" % (mousePoint.x(), mousePoint.y()))


# Initial data frame
x = numpy.linspace(-5., 5., 10000)
y = gaussian(5., 0.2, x)


# Generate layout
win = pg.GraphicsWindow()
label = pg.LabelItem(justify = "right")
win.addItem(label)

p = win.addPlot(row = 1, col = 0)

plot = p.plot(x, y, pen = "y")

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

# Update layout with new data
i = 0
while i < 500:
  noise = numpy.random.normal(0, .2, len(y))
  y_new = y + noise

  plot.setData(x, y_new, pen = "y", clear = True)
  p.enableAutoRange("xy", False)

  pg.QtGui.QApplication.processEvents()

  i += 1

win.close()

1 个答案:

答案 0 :(得分:5)

您需要设置pyqtgraph.SignalProxy并将其连接到回调:

如果p是你的情节,它将如下所示:pyqtgraph.SignalProxy(p.scene().sigMouseMoved, rateLimit=60, slot=callback)

每当鼠标移动到绘图上时,将使用event作为参数调用回调,即callback(event)event[0]包含您传递给p.vb.mapSceneToView(position).x()的x值和p.vb.mapSceneToView(position).y() y值的位置参数。