I'm creating a simple PyQtGraph plot with a legend, and I'd like to disable all interactivity.
I'm able to disable panning and zooming as well as the right-click context menu, but the legend can still be moved. How can I prevent the user from dragging the legend around with the mouse?
import pyqtgraph as pg
widget = pg.plot()
# Disable interactivity
widget.setMouseEnabled(x=False, y=False) # Disable mouse panning & zooming
widget.hideButtons() # Disable corner auto-scale button
widget.getPlotItem().setMenuEnabled(False) # Disable right-click context menu
widget.addLegend(enableMouse=False) # This doesn't disable legend interaction
widget.plot([1, 3, 2, 5, 4], name="Example plot")
if __name__ == "__main__":
pg.exec()
Legend itself implements two mouse events: mouseDragEvent
and hoverEvent
. To disable it, you can simply override it with lambda function, that does nothing.
Also, you might want to disable hide / show functionality of legend. This can be done by overriding legend.sampleType.mouseClickEvent
.
Here is modified code you can use. I left legend.sampleType.mouseClickEvent
commented out:
import pyqtgraph as pg
widget = pg.plot()
# Disable interactivity
widget.setMouseEnabled(x=False, y=False) # Disable mouse panning & zooming
widget.hideButtons() # Disable corner auto-scale button
widget.getPlotItem().setMenuEnabled(False) # Disable right-click context menu
legend = widget.addLegend() # This doesn't disable legend interaction
# Override both methods responsible for mouse events
legend.mouseDragEvent = lambda *args, **kwargs: None
legend.hoverEvent = lambda *args, **kwargs: None
# Uncomment if you want to disable show / hide event of legend click
# legend.sampleType.mouseClickEvent = lambda *args, **kwargs: None
widget.plot([1, 3, 2, 5, 4], name="Example plot")
if __name__ == "__main__":
pg.exec()