Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning mouse cursor coordinates in PyQtGraph

I am new to PyQtGraph and want to use it for a speedy visualization of my data acquisition. Previously I was using matplotlib where redrawing the figure was my bottleneck. After transitioning to PyQtGraph, I am currently missing only one functionality of matplotlib. Namely, returning the x-, and y-coordinate of my mouse cursor.

How can I call/mimic the return of the x-, and y-coordinates of my mouse cursor in a plot made using PyQtGraph?

EDIT! - After implementing the tips of leongold, the code is able to return the mousecursor position without losing speed. The code is the following:

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()
like image 407
The Dude Avatar asked Feb 20 '16 19:02

The Dude


People also ask

How do I find my mouse cursor location?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK.

How do I get the XY coordinates of a mouse Python?

To determine the mouse's current position, we use the statement, pyautogui. position(). This function returns a tuple of the position of the mouse's cursor. The first value is the x-coordinate of where the mouse cursor is.

How do I turn off my cursor coordinates?

You can enable or disable 'view cursor coordinates' using file menu view> showhide> cursorcoordinates.


1 Answers

You need to setup a pyqtgraph.SignalProxy and connect it to a callback:

if p is your plot, it'll look like: pyqtgraph.SignalProxy(p.scene().sigMouseMoved, rateLimit=60, slot=callback)

Whenever the mouse is moved over the plot, the callback is called with an event as an argument, i.e. callback(event). event[0] holds a positional argument you pass to p.vb.mapSceneToView(position).x() for x value and p.vb.mapSceneToView(position).y() for y value.

like image 102
leongold Avatar answered Oct 17 '22 05:10

leongold