'Crosshair appear and disappear on mouse-in and mouse-out
In looking at the crosshair example for pyqtgraph, crosshair.py, the crosshair is always visible, and is moved to the position of the mouse when the mouse is over the plot. This means that the crosshair will get stuck at the corners when the cursor exits the plot. Is there a robust way to turn the crosshair on and off when the mouse is over the plot? There are these sigMouseMoved and sigMouseHover signals, but it's possible to move your mouse out of the window fast enough that sigMouseHover won't fire with an empty argument, so I don't think it's hooked up to mouseLeave.
Solution 1:[1]
To get mouseLeave event use leaveEvent of PlotWidget which inherits from QWidget.LeaveEvent is always fired when cursor leaves, even with fast moving mouse cursor.
Opposite to this function is enterEvent, which we can use to show crosshair again.
Here is working example with hiding / showin crosshair.
import sys
import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication
class CrosshairPlotWidget(pg.PlotWidget):
def __init__(self, parent=None, background='default', plotItem=None, **kargs):
super().__init__(parent=parent, background=background, plotItem=plotItem, **kargs)
self.vLine = pg.InfiniteLine(angle=90, movable=False)
self.hLine = pg.InfiniteLine(angle=0, movable=False)
self.addItem(self.vLine, ignoreBounds=True)
self.addItem(self.hLine, ignoreBounds=True)
self.hLine.hide()
self.vLine.hide()
def leaveEvent(self, ev):
"""Mouse left PlotWidget"""
self.hLine.hide()
self.vLine.hide()
def enterEvent(self, ev):
"""Mouse enter PlotWidget"""
self.hLine.show()
self.vLine.show()
def mouseMoveEvent(self, ev):
"""Mouse moved in PlotWidget"""
if self.sceneBoundingRect().contains(ev.pos()):
mousePoint = self.plotItem.vb.mapSceneToView(ev.pos())
self.vLine.setPos(mousePoint.x())
self.hLine.setPos(mousePoint.y())
if __name__ == "__main__":
app = QApplication(sys.argv)
x = [0, 1, 2, 3, 4, 5]
y = np.random.normal(size=6)
plot = CrosshairPlotWidget()
plot.plot(x, y)
plot.show()
app.exec()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Domarm |
