如何从pyqtgraph中的散点图获取各个点及其属性?

时间:2019-10-28 21:45:40

标签: pyqt python-3.6 pyqtgraph

通过在Qt Designer中将Graphics View窗口小部件升级为PlotWidget,我能够毫不费力地在pyqtgraph中创建ScatterPlotItem。我在上面绘制了一些随机数据,现在我想访问单击的各个点。文档说,可以连接sigClicked(self,points)信号,从理论上讲,该信号应返回光标下的点。但这似乎不是事实,因为当我单击某个点时,无论单击哪个点,我都会得到相同的对象。我怀疑该信号返回了整个ScatterPlotItem,而不是任何特定点。

到目前为止,这是我的代码:

import sys, time
from timeit import default_timer as timer

from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot, Qt, QPoint, QUrl, QEvent
from PyQt5.QtWidgets import *
from PyQt5 import QtMultimedia
from PyQt5.uic import loadUi
import pyqtgraph as pg

import numpy as np

class ScatterExample(QMainWindow):
    def __init__(self):

        # Main Loop
        super(ScatterExample, self).__init__()
        loadUi('<path/to/ui file>.ui', self)
        self.setWindowTitle('ScatterExample')

        self.scatter = pg.ScatterPlotItem(pxMode=False, pen=pg.mkPen(width=1, color='g'), symbol='t', size=1)
        self.scatter.sigClicked.connect(self.onPointsClicked)
        self.Scatter_Plot_View.addItem(self.scatter) # Scatter_Plot_View is the Graphics View I promoted to PlotWidget
        n = 5
        print('Number of points: ' + str(n))
        data = np.random.normal(size=(2, n))
        pos = [{'pos': data[:, i]} for i in range(n)]

        now = pg.ptime.time()
        self.scatter.setData(pos)
        print(self.scatter.data)


    def onPointsClicked(self, points):
        print('Ain\'t getting individual points ', points)
        points.setPen('b', width=2) # this turns EVERY point blue, not just the one clicked.

上面的打印语句打印:

Ain't getting individual points <pyqtgraph.graphicsItems.ScatterPlotItem.ScatterPlotItem object at 0x000001C36577F948>

如何获取单击的点及其相应的属性,例如x和y坐标?

1 个答案:

答案 0 :(得分:0)

由于eyllansec很善于建议,我将def onPointsClicked(self, points):更改为def onPointsClicked(self, obj, points):,现在pyqtgraph可以正常工作了。