简体   繁体   English

将像素/场景坐标(从 MouseClickEvent)转换为 plot 坐标

[英]Convert pixel/scene coordinates (from MouseClickEvent) to plot coordinates

I have a GraphicsLayoutWidget to which I added a PlotItem .我有一个GraphicsLayoutWidget ,我在其中添加了一个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:因此,我将信号sigMouseClicked连接到一个自定义方法,如下所示:

...
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]).虽然这给了我看起来像Point (697.000000, 882.000000)的坐标,但我很难将它们转换为图形的“轴”坐标中的坐标(例如,轴在 [0.1] 范围内的 (0.3, 0.5))。 I tried many mapTo/From* methods without success.我尝试了许多 mapTo/From* 方法但没有成功。

Is there any way to archive this with PyQtGraph?有什么方法可以用 PyQtGraph 存档吗?

You have to use the viewbox of the plotitem:您必须使用 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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