将 pixel/scene 坐标(来自 MouseClickEvent)转换为绘图坐标
Convert pixel/scene coordinates (from MouseClickEvent) to plot coordinates
我有一个 GraphicsLayoutWidget,我在其中添加了一个 PlotItem。我有兴趣点击图表中的某处(而不是在曲线或项目上)并在图表坐标中获取点击点。因此,我将信号 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()})
...
虽然这给我的坐标看起来像点 (697.000000, 882.000000),我很难将它们转换为图形“轴”坐标中的坐标(例如,轴在 [0.1] 范围内的 (0.3, 0.5))。我尝试了很多 mapTo/From* 方法都没有成功。
有什么方法可以用 PyQtGraph 存档吗?
您必须使用 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()
我有一个 GraphicsLayoutWidget,我在其中添加了一个 PlotItem。我有兴趣点击图表中的某处(而不是在曲线或项目上)并在图表坐标中获取点击点。因此,我将信号 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()})
...
虽然这给我的坐标看起来像点 (697.000000, 882.000000),我很难将它们转换为图形“轴”坐标中的坐标(例如,轴在 [0.1] 范围内的 (0.3, 0.5))。我尝试了很多 mapTo/From* 方法都没有成功。
有什么方法可以用 PyQtGraph 存档吗?
您必须使用 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()