def initialize(self, edge_id): edge = graph.edge(edge_id) if edge is not None: self._id = edge_id self._direction = edge.direction() if self._begin is not None: self._begin.positionChanged.disconnect(self.onItemMove) if self._end is not None: self._end.positionChanged.disconnect(self.onItemMove) self._begin = self.scene().node(edge.head().id()) self._end = self.scene().node(edge.tail().id()) self._begin.positionChanged.connect(self.onItemMove) self._end.positionChanged.connect(self.onItemMove) self._calculate()
def _calculate(self): p1 = self.mapFromItem(self._begin, 0, 0) p2 = self.mapFromItem(self._end, 0, 0) line = QLineF(p1, p2) distance = line.length() line = line.unitVector() center = line.unitVector() center.setLength(distance * 0.5) center = center.p2() line.setLength(self._begin.radius()) self._beginPoint = line.p2() line = QLineF(p2, p1).unitVector() line.setLength(self._end.radius()) self._endPoint = line.p2() line = QLineF(self._endPoint, self._beginPoint) self.setLine(line) l = line.length() self._path = QGraphicsLineItem.shape(self) # self._path = QPainterPath() # QGraphicsLineItem.shape(self) # self._path.moveTo(self._beginPoint) # ln = line.unitVector() # ln.setLength(l * 0.5) # c = ln.p2() # c.setX(c.x() + l * float(randint(-100, 100)) / 300.0) # c.setY(c.y() + l * float(randint(-100, 100)) / 300.0) # self._path.quadTo(c, self._endPoint) # self._path.addEllipse(c, 5, 5) if self._direction == EdgeDirection.STRAIGHT and l > 0.01: angle = acos(line.dx() / l) if line.dy() >= 0: angle = pi * 2.0 - angle p1 = line.p1() + QPointF(sin(angle + Edge._arrowAngle) * Edge._arrowSize, cos(angle + Edge._arrowAngle) * Edge._arrowSize) p2 = line.p1() + QPointF(sin(angle + pi - Edge._arrowAngle) * Edge._arrowSize, cos(angle + pi - Edge._arrowAngle) * Edge._arrowSize) arrow = QPolygonF() arrow.append(p1) arrow.append(line.p1()) arrow.append(p2) self._path.addPolygon(arrow) edge = graph.edge(self._id) if edge is not None: w = int(max(distance, 1)) edge.set_base_weight(w) if self._text is None: self._text = QGraphicsSimpleTextItem(str(w), self) else: self._text.setText(str(w)) self._text.setPos(center)
def onDirectionChange(self): edge = graph.edge(self._id) if edge is not None: if self._direction != edge.direction(): self._direction = edge.direction() self._calculate()