可移动的 QGraphicsLineItem 边界框

Movable QGraphicsLineItem bounding box

我正在尝试将可拖动的 QtGui.QGraphicsLineItem 添加到 pyqtgraph.plotItem。

从 PyQt4 导入 QtCore、QtGui 将 pyqtgraph 导入为 pg

app = QtGui.QApplication([])

w = pg.PlotWidget()
w.show()

line = QtGui.QGraphicsLineItem()
line.setFlag(QtGui.QGraphicsItem.ItemIsMovable)
line.setPen(QtGui.QPen(QtGui.QColor(255, 0, 0), 2))
line.setLine(0, 0, 100, 100)

w.plotItem.addItem(line)

app.exec_()

但是,存在几个问题: - 绘图缩放时线宽会发生变化 - 拖动开始的区域包括整个矩形边界框(见下图)

我尝试了以下技巧: 1)

line.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations)
w.plotItem.addItem(line)

2)

line.setParentItem(w.plotItem.vb)

但是拖动区域问题依然存在

您可以使用 pyqtgraph 中的 LineSegmentRoi

line = pg.LineSegmentROI([0, 100], [0, 0], pen=(255, 0, 0))
w.plotItem.addItem(line)

好的,这里是解决方案。当我们使用 QtGui.QGraphicsLineItem:

1) 对于"line width changes when the plot is zoomed"问题, 使用 pen.setCosmetic(True) 或使用 pg.mkPen

创建笔

2) 对于"area where the dragging starts includes the whole rectangle bounding box (see picture below)"问题, 使用 mouseDragEvent 而不是使用 line.setFlag(QtGui.QGraphicsItem.ItemIsMovable)