简体   繁体   中英

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 eg Point (697.000000, 882.000000) , I struggle to convert them to coordinates in "axes" coordinates of the graph (eg (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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM