PyQtGraph PolyLineROI maxBounds 不工作

PyQtGraph PolyLineROI maxBounds Not Working

我在 PlotItem 中有一个 PolyLineROI,我试图将手柄限制为仅在绘图范围内移动。我尝试使用 maxBounds 参数,但这不起作用(句柄仍然移到图形之外):

代码:

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore

app = pg.mkQApp('Plot')

window = pg.GraphicsLayoutWidget(show=True, size=(400,400), border=False, title='Plot')
plt = window.addPlot(title='Plot')

polyline = pg.PolyLineROI(
    [[0,0], [10,10], [10,30], [30,10]],
    closed=False,
    maxBounds=QtCore.QRectF(0,0,30,30)
)

plt.addItem(polyline)

plt.disableAutoRange('xy')
plt.autoRange()

if __name__ == "__main__":
    pg.exec()

问题:

我在这些邮件列表中看到了这个问题:

  1. Google Group
  2. Mail Archive Google Group

但他们没有任何答案,这里也没有问过这个问题。

如何防止图柄移出图形边界?

为此,您必须继承 PolyLineROI 并覆盖 checkPointMove:

代码:

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore

class GraphPolyLine(pg.PolyLineROI):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def checkPointMove(self, handle, pos, modifiers):
        if self.maxBounds is not None:
            pt = self.getViewBox().mapSceneToView(pos)
        
            if not self.maxBounds.contains(pt.x(), pt.y()):
                return False

        return True

app = pg.mkQApp("ROI Examples")

window = pg.GraphicsLayoutWidget(show=True, size=(400,400), border=False, title='Plot')

plt = window.addPlot(title="Plot")
plt.setMouseEnabled(False, False)  # Disable zoom and pan

polyline = GraphPolyLine(
    [[0,0], [10,10], [10,30], [30,10]],
    closed=False,
    maxBounds = QtCore.QRectF(0, 0, 30, 30)
)

plt.addItem(polyline)
plt.disableAutoRange('xy')
plt.autoRange()

if __name__ == "__main__":
    pg.exec()

解法:

pyqtgraph.graphicsItems.ROI,我们看到