各位应该都会在scene中画直线,但部分需求场景下,两个item之间需要使用带箭头的直线来进行连接,表明前后关系。核心就是计算出箭头的三个点的位置,并使用painter.drawPolygon()
来进行绘制。
效果图:
源码:
# 类中的属性
# 为连线添加箭头
self._mark_pen = QPen(Qt.black)
self._mark_pen.setWidthF(self.width)
self._mark_brush = QBrush()
self._mark_brush.setColor(Qt.black)
self._mark_brush.setStyle(Qt.SolidPattern)
self.width = 3.0 # 线条的宽度
self.pos_src = [0, 0] # 线条起始位置 x,y坐标
self.pos_dst = [0, 0] # 线条结束位置
# override
def paint(self, painter, widget=None):
self.setPath(self.calcPath()) # 设置路径
path = self.path()
x1, y1 = self.pos_src
x2, y2 = self.pos_dst
length = 30 # 圆点距离终点图元的距离
k = math.atan2(y2 - y1, x2 - x1) # theta
new_x = x2 - length * math.cos(k) # 减去线条自身的宽度
new_y = y2 - length * math.sin(k)
new_x1 = new_x - 20 * math.cos(k - np.pi / 6)
new_y1 = new_y - 20 * math.sin(k - np.pi / 6)
new_x2 = new_x - 20 * math.cos(k + np.pi / 6)
new_y2 = new_y - 20 * math.sin(k + np.pi / 6)
# 先画最终路径
painter.setPen(self._pen)
painter.drawPath(path)
# 再画圆点
painter.setPen(self._mark_pen)
painter.setBrush(self._mark_brush)
point1 = QPoint(new_x, new_y)
point2 = QPoint(new_x1, new_y1)
point3 = QPoint(new_x2, new_y2)
painter.drawPolygon(point1, point2, point3)