yurumi
yurumi

Reputation: 3

Convert pixel/scene coordinates (from MouseClickEvent) to plot coordinates

I have a GraphicsLayoutWidget to which I added a PlotItem. I'm interested in clicking somewhere in the graph (not on a curve or item) and getting the clicked point in graph coordinates. Therefore I connected the signal sigMouseClicked to a custom method something like this:

...
self.graphics_view = pg.GraphicsLayoutWidget()
self.graphics_view.scene().sigMouseClicked.connect(_on_mouse_clicked)

def _on_mouse_clicked(event):
    print(f'pos: {event.pos()}  scenePos: {event.scenePos()})
...

While this gives me coordinates that look like e.g. Point (697.000000, 882.000000), I struggle to convert them to coordinates in "axes" coordinates of the graph (e.g. (0.3, 0.5) with axes in the range [0.1]). I tried many mapTo/From* methods without success.

Is there any way to archive this with PyQtGraph?

Upvotes: 0

Views: 480

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

You have to use the viewbox of the plotitem:

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


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.graphics_view = pg.GraphicsLayoutWidget()

        self.setCentralWidget(self.graphics_view)

        self.plot_item = self.graphics_view.addPlot()
        curve = self.plot_item.plot()
        curve.setData([0, 0, 1, 1, 2, 2, 3, 3])

        self.graphics_view.scene().sigMouseClicked.connect(self._on_mouse_clicked)

    def _on_mouse_clicked(self, event):
        p = self.plot_item.vb.mapSceneToView(event.scenePos())
        print(f"x: {p.x()}, y: {p.y()}")


def main():
    app = QtGui.QApplication([])

    w = MainWindow()
    w.show()

    app.exec_()


if __name__ == "__main__":
    main()

Upvotes: 2

Related Questions