def initMap(self): features = json.load(open("Data/world.json", encoding="utf8")).get("features") for feature in features: geometry = feature.get("geometry") if not geometry: continue _type = geometry.get("type") coordinates = geometry.get("coordinates") for coordinate in coordinates: if _type == "Polygon": polygon = QPolygonF([ QPointF(latitude, -longitude) for latitude, longitude in coordinate ]) item = QGraphicsPolygonItem(polygon) item.setPen(QPen(self.borderColor, 0)) item.setBrush(QBrush(self.backgroundColor)) item.setPos(0, 0) self._scene.addItem(item) elif _type == "MultiPolygon": for _coordinate in coordinate: polygon = QPolygonF([ QPointF(latitude, -longitude) for latitude, longitude in _coordinate ]) item = QGraphicsPolygonItem(polygon) item.setPen(QPen(self.borderColor, 0)) item.setBrush(QBrush(self.backgroundColor)) item.setPos(0, 0) self._scene.addItem(item)
def on_actItem_Polygon_triggered(self): # 添加一个梯形 item = QGraphicsPolygonItem() points = QPolygonF() points.append(QPointF(-40, -40)) points.append(QPointF(40, -40)) points.append(QPointF(100, 40)) points.append(QPointF(-100, 40)) item.setPolygon(points) item.setPos(-50 + (QtCore.qrand() % 100), -50 + (QtCore.qrand() % 100)) item.setFlags(QGraphicsItem.ItemIsMovable | QGraphicsItem.ItemIsSelectable | QGraphicsItem.ItemIsFocusable) item.setBrush(QBrush(Qt.green)) self.view.frontZ = self.view.frontZ + 1 item.setZValue(self.view.frontZ) self.view.seqNum = self.view.seqNum + 1 item.setData(self.view.ItemId, self.view.seqNum) # //自定义数据,ItemId键 item.setData(self.view.ItemDesciption, "梯形") self.scene.addItem(item) self.scene.clearSelection() item.setSelected(True)
class Triangle(QGraphicsView): def __init__(self, x1, y1, x2, y2, x3, y3): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.x3 = x3 self.y3 = y3 triangle = QtGui.QPolygonF(3) triangle[0] = QtCore.QPoint(self.x1, self.y1) triangle[1] = QtCore.QPoint(self.x2, self.y2) triangle[2] = QtCore.QPoint(self.x3, self.y3) self.triangle = QGraphicsPolygonItem(triangle) def draw_triangle(self, scene): scene.addItem(self.triangle) def move_triangle(self, m, n): self.triangle.setPos(m, n) def rotate_triangle(self, r): self.triangle.setRotation(r) def scale_triangle(self, s): self.triangle.setScale((s + 50) / 100) def recolor_triangle(self, r, g, b): self.triangle.setBrush(QColor(r, g, b))
def on_qAction16_triggered(self): item = QGraphicsPolygonItem() points = [ QPointF(-40, -40), QPointF(40, -40), QPointF(100, 40), QPointF(-100, 40) ] item.setPolygon(QPolygonF(points)) item.setBrush(QBrush(Qt.green)) self.__setItemProperties(item, "梯形")
def create_arrow(tile): item = QGraphicsPolygonItem(qt_drawings.arrow_polygon) item.setPen(qt_drawings.no_pen) if tile: item.setBrush(qt_drawings.cyan_brush if tile.is_frozen else qt_drawings.black_brush) item.setTransformOriginPoint(qt_drawings.tile_size / 2, qt_drawings.tile_size / 2) angle = base_scene_reactor.tile_rotation_angles[tile.is_horizontal][tile.is_positive] item.setRotation(angle) else: item.setBrush(qt_drawings.black_brush) return item
class RPolygon(QObject): def __init__(self, points, color, line_width): self._points = [QPointF(p[0], p[1]) for p in points] self._pos = self._points[0] super().__init__() # The underlying QGraphicsPolygonItem self.polygon = QGraphicsPolygonItem() self.polygon.setPolygon(QPolygonF(self._points)) self.polygon.setBrush(QtGui.QBrush(color)) pen = QPen() pen.setWidthF(line_width) self.polygon.setPen(pen) self._visible = 1 def x(self): return self._pos.x() def y(self): return self._pos.y() def points(self): return self._points # The following functions are for animation support @pyqtProperty(QPointF) def pos(self): return self._pos @pos.setter def pos(self, value): delta_x = value.x() - self._pos.x() delta_y = value.y() - self._pos.y() self._points = [ QPointF(p.x() + delta_x, p.y() + delta_y) for p in self._points ] self.polygon.setPolygon(QPolygonF(self._points)) self._pos = value @pyqtProperty(int) def visible(self): return self._visible @visible.setter def visible(self, value): if (value > 0): self.polygon.show() else: self.polygon.hide() self._visible = value
def draw_polygons(self): sf = shapefile.Reader(self.shapefile) polygons = sf.shapes() for polygon in polygons: # convert shapefile geometries into shapely geometries # to extract the polygons of a multipolygon polygon = shapely.geometry.shape(polygon) # if it is a polygon, we use a list to make it iterable if polygon.geom_type == 'Polygon': polygon = [polygon] for land in polygon: qt_polygon = QPolygonF() for lon, lat in land.exterior.coords: px, py = self.to_canvas_coordinates(lon, lat) if px > 1e+10: continue qt_polygon.append(QPointF(px, py)) polygon_item = QGraphicsPolygonItem(qt_polygon) polygon_item.setBrush(self.land_brush) polygon_item.setPen(self.land_pen) polygon_item.setZValue(1) yield polygon_item
def draw_polygons(self): sf = shapefile.Reader(self.shapefile) polygons = sf.shapes() for polygon in polygons: # convert shapefile geometries into shapely geometries # to extract the polygons of a multipolygon polygon = shapely.geometry.shape(polygon) # if it is a polygon, we use a list to make it iterable if polygon.geom_type == 'Polygon': polygon = [polygon] for land in polygon: qt_polygon = QPolygonF() land = str(land)[10:-2].replace(', ', ',').replace(' ', ',') coords = land.replace('(', '').replace(')', '').split(',') for lon, lat in zip(coords[0::2], coords[1::2]): px, py = self.to_canvas_coordinates(lon, lat) if px > 1e+10: continue qt_polygon.append(QPointF(px, py)) polygon_item = QGraphicsPolygonItem(qt_polygon) polygon_item.setBrush(self.land_brush) polygon_item.setPen(self.land_pen) polygon_item.setZValue(1) yield polygon_item
def create_element_model(self, gscene): clut = rgbt.RGBTable(filename='gui/red_blue64.csv', data_range=[10.0, 100.]) ele_model = ele.ElementModel() ele_model.elements_from_sequence(self.seq_model) pen = QPen() pen.setCosmetic(True) for e in ele_model.elements: poly = e.shape() polygon = QPolygonF() for p in poly: polygon.append(QPointF(p[0], p[1])) gpoly = QGraphicsPolygonItem() gpoly.setPolygon(polygon) # set element color based on V-number gc = float(e.medium.glass_code()) vnbr = round(100.0 * (gc - int(gc)), 3) ergb = clut.get_color(vnbr) gpoly.setBrush(QColor(*ergb)) gpoly.setPen(pen) t = e.tfrm[1] gpoly.setPos(QPointF(t[2], -t[1])) gscene.addItem(gpoly)
def create_ray_model(self, gscene, start_surf=1): tfrms = self.seq_model.compute_global_coords(start_surf) rayset = self.seq_model.trace_boundary_rays() start_offset = 0.1 * gscene.sceneRect().width() if abs(tfrms[0][1][2]) > start_offset: tfrms[0] = self.seq_model.shift_start_of_rayset( rayset, start_offset) pen = QPen() pen.setCosmetic(True) for rays in rayset: poly1 = [] for i, r in enumerate(rays[3][0][0:]): rot, trns = tfrms[i] p = rot.dot(r[0]) + trns # print(i, r[0], rot, trns, p) poly1.append(QPointF(p[2], -p[1])) poly2 = [] for i, r in enumerate(rays[4][0][0:]): rot, trns = tfrms[i] p = rot.dot(r[0]) + trns # print(i, r[0], rot, trns, p) poly2.append(QPointF(p[2], -p[1])) poly2.reverse() poly1.extend(poly2) polygon = QPolygonF() for p in poly1: polygon.append(p) gpoly = QGraphicsPolygonItem() gpoly.setPolygon(polygon) gpoly.setBrush(QColor(254, 197, 254, 64)) # magenta, 25% gpoly.setPen(pen) gscene.addItem(gpoly)
class NozzlePreviewWidget(QWidget): def __init__(self): super().__init__() self.ui = Ui_NozzlePreview() self.ui.setupUi(self) self.brush = QBrush() self.brush.setStyle(1) self.scene = QGraphicsScene(self) self.upper = QGraphicsPolygonItem() self.lower = QGraphicsPolygonItem() self.upper.setBrush(self.brush) self.lower.setBrush(self.brush) self.scene.addItem(self.upper) self.scene.addItem(self.lower) self.ui.tabCrossSection.setScene(self.scene) self.ui.tabWidget.currentChanged.connect(self.rescale) def loadNozzle(self, nozzle): geomAlerts = nozzle.getGeometryErrors() self.ui.tabAlerts.clear() for err in geomAlerts: self.ui.tabAlerts.addItem(err.description) self.upper.setPolygon(QPolygonF([])) self.lower.setPolygon(QPolygonF([])) for alert in geomAlerts: if alert.level == motorlib.simResult.SimAlertLevel.ERROR: return convAngle = radians(nozzle.props['convAngle'].getValue()) throatLen = nozzle.props['throatLength'].getValue() throatRad = nozzle.props['throat'].getValue() / 2 divAngle = radians(nozzle.props['divAngle'].getValue()) exitRad = nozzle.props['exit'].getValue() / 2 outerRad = 1.25 * exitRad if QApplication.instance() and QApplication.instance( ).fileManager: # Check if the app exists and has a fm motor = QApplication.instance().fileManager.getCurrentMotor() if len(motor.grains) > 0: outerRad = motor.grains[0].getProperty('diameter') / 2 scale = 100 / nozzle.props['exit'].getValue() radDiff = exitRad - throatRad if divAngle != 0: divLen = radDiff / tan(divAngle) else: divLen = 0 if convAngle != 0: convLen = (outerRad - throatRad) / tan(convAngle) else: convLen = 0 upperPoints = [ [throatLen, throatRad], [0, throatRad], [-divLen, exitRad], [-divLen, outerRad], [throatLen + convLen, outerRad], ] lower = QPolygonF( [QPointF(p[0] * scale, p[1] * scale) for p in upperPoints]) upper = QPolygonF( [QPointF(p[0] * scale, -p[1] * scale) for p in upperPoints]) self.upper.setPolygon(upper) self.lower.setPolygon(lower) self.rescale() def rescale(self): self.scene.setSceneRect(self.scene.itemsBoundingRect()) self.ui.tabCrossSection.fitInView(self.scene.sceneRect(), Qt.KeepAspectRatio)
class RelationItem(): ''' This represents one relationship on the diagram. This class creates the arc graphics item and the text graphics item and draws them on the scene. The RelationInstance class manages reading and writing the relationship to Neo4j ''' def __init__(self, scene, relationInstance=None): self.scene = scene self.model = self.scene.parent.model self.diagramType = "Instance Relationship" self.logMsg = None # self.relationInstance should have been called self.itemInstance to be consistent # with NodeItem. so we'll set it to none and someday fix this. self.itemInstance = None self.relationInstance = relationInstance self.startNZID = self.relationInstance.startNZID self.endNZID = self.relationInstance.endNZID # get the NodeItem objects for the start and end nodes self.startNode = self.scene.parent.itemDict[self.startNZID] self.endNode = self.scene.parent.itemDict[self.endNZID] self.numRels = self.scene.parent.numRels(self.relationInstance.startNZID, self.relationInstance.endNZID) # print("numRels:{}".format(self.numRels)) self.lineType = None # print("num rels{}".format(str(self.numRels))) # initialize the two qgraphicsitems needed to draw a relationship to None self.IRel = None self.IRtext = None self.bunnyEar = None self.endDot = None self.arrowHead = None self.TAline1 = None self.TAline2 = None self.debugTriangle = None self.drawRelationship() def name(self, ): return self.relationInstance.NZID def NZID(self, ): return self.relationInstance.NZID def getFormat(self, ): ''' determine if the rel instance has a template format or should use the project default format ''' # get the default self.relFormat = IRelFormat(formatDict=self.model.modelData["IRformat"]) # get a custom template format if there is one if not self.relationInstance.relTemplate is None: index, relTemplateDict = self.model.getDictByName(topLevel="Relationship Template",objectName=self.relationInstance.relTemplate) if not relTemplateDict is None: self.instanceRelFormatDict = relTemplateDict.get("IRformat", None) if not self.instanceRelFormatDict is None: self.relFormat = IRelFormat(formatDict=self.instanceRelFormatDict) def getNodeId(self): '''return the rel id for the relationship from the IREL or bunnyear graphic item - which ever it is ''' if not self.IRel is None: nodeID = self.IRel.data(NODEID) elif not self.bunnyEar is None: nodeID = self.bunnyEar.data(NODEID) else: nodeID = None return nodeID def clearItem(self, ): if (not self.IRel is None and not self.IRel.scene() is None): self.IRel.scene().removeItem(self.IRel) if (not self.IRtext is None and not self.IRtext.scene() is None): self.IRtext.scene().removeItem(self.IRtext) if (not self.bunnyEar is None and not self.bunnyEar.scene() is None): self.bunnyEar.scene().removeItem(self.bunnyEar) if (not self.endDot is None and not self.endDot.scene() is None): self.endDot.scene().removeItem(self.endDot) if (not self.arrowHead is None and not self.arrowHead.scene() is None): self.arrowHead.scene().removeItem(self.arrowHead) if (not self.TAline2 is None and not self.TAline2.scene() is None): self.TAline2.scene().removeItem(self.TAline2) if (not self.TAline1 is None and not self.TAline1.scene() is None): self.TAline1.scene().removeItem(self.TAline1) # if (not self.debugTriangle is None and not self.debugTriangle.scene() is None): # self.debugTriangle.scene().removeItem(self.debugTriangle) def drawIt(self, ): ''' for consistency, drawIt should be used instead of drawRelationship ''' self.drawRelationship() def drawRelationship(self, ): # relationship is between two different nodes if self.startNZID != self.endNZID: # set the line type if it hasn't been determined yet. This happens on first draw if self.lineType is None: if self.scene.parent.anyRels(self.relationInstance.startNZID, self.relationInstance.endNZID): self.lineType = CURVE else: self.lineType = STRAIGHT # now draw the line or arc if self.lineType == CURVE: self.drawRel() else: self.drawStraightRel() # relationship is between the same node if self.startNZID == self.endNZID: self.drawBunnyEars() def drawBunnyEars(self, ): # force the rel instance to update its values in case it has been updated from another diagram or the tree view self.relationInstance.reloadDictValues() # get the format in case it changed self.getFormat() # if the arc and text graphics items already exist on the scene then delete them self.clearItem() # draw the relationship arc pen = self.relFormat.pen() brush = self.relFormat.brush() brush.setColor(QColor(Qt.white)) # create an ellipse like the startNode x = self.startNode.INode.sceneBoundingRect().center().x() y = self.startNode.INode.sceneBoundingRect().center().y() w = self.startNode.INode.sceneBoundingRect().width()/2.0 h = self.startNode.INode.sceneBoundingRect().height()/2.0 myEllipse = Ellipse(x, y, w, h) # move the bunny ears around the ellipse until we run out of room startDegree = 360 - (self.numRels * 40) if startDegree < 40: startDegree = 40 startPoint = myEllipse.pointFromAngle(radians(startDegree)) endPoint = myEllipse.pointFromAngle(radians(startDegree-35)) lineMidPoint = centerLine (startPoint[0], startPoint[1], endPoint[0], endPoint[1]) lineDist = distanceLine (startPoint[0], startPoint[1], endPoint[0], endPoint[1]) circleRad = lineDist/2.0 self.bunnyEar = QGraphicsEllipseItem(QRectF(lineMidPoint[0]-circleRad,lineMidPoint[1]-circleRad,circleRad*2,circleRad*2), parent=None) self.bunnyEar.setZValue(RELATIONLAYER) self.bunnyEar.setBrush(brush) self.bunnyEar.setPen(pen) self.bunnyEar.setFlag(QGraphicsItem.ItemIsMovable, True) self.bunnyEar.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.bunnyEar.setFlag(QGraphicsItem.ItemIsSelectable, False) self.bunnyEar.setSelected(False) # create arrowhead self.circlex = lineMidPoint[0] self.circley = lineMidPoint[1] # self.circleDot = QGraphicsEllipseItem(QRectF(self.circlex-1.5,self.circley-1.5,3, 3), parent=None) # self.circleDot.setZValue(NODELAYER) # self.scene.addItem(self.circleDot) # self.pointDot = QGraphicsEllipseItem(QRectF(endPoint[0]-1.5,endPoint[1]-1.5,3, 3), parent=None) # self.pointDot.setZValue(NODELAYER) # self.scene.addItem(self.pointDot) # compute the arrow base center point arrowLen = 5 # this is half the distance of the arrowhead base which determines how wide the arrow head is # compute a point on the arc that is a short distance away from the edge of the ellipse. this is the base of the arrow head # get the slope of the line from the start point to the end point on the node ellipse if endPoint[0] == startPoint[0]: startPoint[0] = startPoint[0] + .001 # slope1 = (startPoint[1] - endPoint[1])/(startPoint[0] - endPoint[0]) slope1 = (endPoint[1] - startPoint[1] )/(endPoint[0] - startPoint[0]) if slope1 == 1.0: slope1 = 1.001 slope1Squared = slope1 * slope1 perpSlope1 = -1.0 / slope1 perpSlope1Squared = perpSlope1 * perpSlope1 # print("numrels:{} startDegree:{} radius:{} slope:{} perpslope:{}".format(self.numRels, startDegree, circleRad, slope1, perpSlope1)) # now find a point on the line tangent to the point on the bunny ear circle. This is the base of the arrow # ax = (arrowLen / sqrt(1 + (perpSlope1Squared))) # ay = ax * perpSlope1 if lineMidPoint[0] < x: baseX = endPoint[0] - (arrowLen / sqrt(1 + (perpSlope1Squared))) baseY = endPoint[1] - ((arrowLen / sqrt(1 + (perpSlope1Squared))) * perpSlope1 ) else: baseX = endPoint[0] + (arrowLen / sqrt(1 + (perpSlope1Squared))) baseY = endPoint[1] + ((arrowLen / sqrt(1 + (perpSlope1Squared))) * perpSlope1 ) # print("ax:{} ay:{} slope1:{} perslope1:{}".format(ax, ay, slope1, perpSlope1)) # self.anchorDot = QGraphicsEllipseItem(QRectF(baseX-1.5,baseY-1.5,3, 3), parent=None) # self.anchorDot.setZValue(NODELAYER) # self.scene.addItem(self.anchorDot) # get first arrowhead base corner ab1dx = (arrowLen / sqrt(1 + (slope1Squared))) ab1dy = ab1dx * slope1 self.b1x = baseX + ab1dx self.b1y = baseY + ab1dy # get 2nd arrowhead base corner ab2dx = (arrowLen / sqrt(1 + (slope1Squared))) ab2dy = ab2dx * slope1 self.b2x = baseX - ab2dx self.b2y = baseY - ab2dy # # calculate the arrowhead points # cx = self.endNode.INode.sceneBoundingRect().center().x() # cy = self.endNode.INode.sceneBoundingRect().center().y() # self.calcArrowHead(QPointF(cx, cy), QPointF( endPoint[0], endPoint[1]), bunnyEars=True) #create an empty polygon arrowPolygon = QPolygonF() # # add arrowhead points # arrowPolygon.append(QPointF(self.ah1x, self.ah1y)) # arrowPolygon.append(QPointF(endPoint[0], endPoint[1])) # arrowPolygon.append(QPointF(self.ah2x, self.ah2y)) # add arrowhead points arrowPolygon.append(QPointF(self.b1x, self.b1y)) arrowPolygon.append(QPointF(endPoint[0], endPoint[1])) arrowPolygon.append(QPointF(self.b2x, self.b2y)) self.arrowHead = QGraphicsPolygonItem(arrowPolygon, parent=None, ) self.arrowHead.setZValue(RELATIONLAYER) self.arrowHead.setBrush(brush) self.arrowHead.setPen(pen) self.arrowHead.setFlag(QGraphicsItem.ItemIsMovable, True) self.arrowHead.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.arrowHead.setFlag(QGraphicsItem.ItemIsSelectable, False) self.arrowHead.setSelected(False) # set data in the bunnyEar object self.bunnyEar.setData(NODEID, self.relationInstance.NZID) self.bunnyEar.setData(ITEMTYPE, RELINSTANCEARC) self.scene.addItem(self.bunnyEar) self.scene.addItem(self.arrowHead) # calculate position of text bunnyEllipse = Ellipse(lineMidPoint[0],lineMidPoint[1],circleRad,circleRad) # use the same midpoint angle as the bunny ear start and end point bunnyMidPoint = bunnyEllipse.pointFromAngle(radians(startDegree-17.5)) # draw the text self.drawText(bunnyMidPoint[0], bunnyMidPoint[1], startPoint[0], startPoint[1], endPoint[0], endPoint[1]) # self.anchorDot = QGraphicsEllipseItem(QRectF(bunnyMidPoint[0]-1.5,bunnyMidPoint[1]-1.5,3, 3), parent=None) # self.anchorDot.setZValue(NODELAYER) # self.scene.addItem(self.anchorDot) def drawStraightRel(self): # print("draw straight rel") # force the rel instance to update its values in case it has been updated from another diagram or the tree view self.relationInstance.reloadDictValues() # get the format in case it changed self.getFormat() # if the arc and text graphics items already exist on the scene then delete them self.clearItem() # draw the relationship arc pen = self.relFormat.pen() brush = self.relFormat.brush() # get the centerpoint of the end node cx = self.endNode.INode.sceneBoundingRect().center().x() cy = self.endNode.INode.sceneBoundingRect().center().y() # get the start and end points of the line esx, esy, eex, eey = self.calcLine3() # create the arc qgraphicsitem self.IRel = QGraphicsLineItem(esx, esy, eex, eey, parent=None) arrowLine = self.IRel # text location tx = self.IRel.line().pointAt(.5).x() ty = self.IRel.line().pointAt(.5).y() # draw the relationship line pen = self.relFormat.pen() # configure the lines and add them to the scene self.IRel.setPen(pen) self.IRel.setZValue(RELATIONLAYER) self.IRel.setData(NODEID, self.relationInstance.NZID) self.IRel.setData(ITEMTYPE, RELINSTANCEARC) self.IRel.setFlag(QGraphicsItem.ItemIsSelectable, True) self.scene.addItem(self.IRel) # line arrowhead # compute the arrow base center point arrowLen = 5 # this is half the distance of the arrowhead base which determines how wide the arrow head is # compute a point on the arc that is a short distance away from the edge of the ellipse. this is the base of the arrow head ax = self.IRel.line().pointAt(1-(10.0/self.IRel.line().length())).x() ay = self.IRel.line().pointAt(1-(10.0/self.IRel.line().length())).y() # compute the arrow base corners if eex == ax: ax = ax + .001 # get the slope of the line from the ellipse to the arrowhead base slope = (eey - ay)/(eex - ax) if slope == 1.0: slope = 1.001 # get the perpindicular slope perpSlope = -1.0 / slope perpSlopeSquared = perpSlope * perpSlope # get first arrowhead base corner ab1dx = (arrowLen / sqrt(1 + (perpSlopeSquared))) ab1dy = ab1dx * perpSlope self.b1x = ax + ab1dx self.b1y = ay + ab1dy # get 2nd arrowhead base corner ab2dx = (arrowLen / sqrt(1 + (perpSlopeSquared))) ab2dy = ab2dx * perpSlope self.b2x = ax - ab2dx self.b2y = ay - ab2dy #create an empty polygon arrowPolygon = QPolygonF() # add arrowhead points arrowPolygon.append(QPointF(self.b1x, self.b1y)) arrowPolygon.append(QPointF(eex, eey)) arrowPolygon.append(QPointF(self.b2x, self.b2y)) self.arrowHead = QGraphicsPolygonItem(arrowPolygon, parent=None, ) self.arrowHead.setZValue(RELATIONLAYER) self.arrowHead.setBrush(brush) self.arrowHead.setPen(pen) self.arrowHead.setFlag(QGraphicsItem.ItemIsMovable, True) self.arrowHead.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.arrowHead.setFlag(QGraphicsItem.ItemIsSelectable, False) self.arrowHead.setSelected(False) self.scene.addItem(self.arrowHead) # draw the text self.drawText(tx, ty, esx, esy, eex, eey) def drawRel(self, ): # draw the curved relationship line # print("draw curve rel") # force the rel instance to update its values in case it has been updated from another diagram or the tree view self.relationInstance.reloadDictValues() # get the format in case it changed self.getFormat() # if the arc and text graphics items already exist on the scene then delete them self.clearItem() # draw the relationship arc pen = self.relFormat.pen() brush = self.relFormat.brush() # METHOD 1 use ellipse center points # # get the center points of the qgraphicellipses # sx = self.startNode.INode.sceneBoundingRect().center().x() # sy = self.startNode.INode.sceneBoundingRect().center().y() # ex = self.endNode.INode.sceneBoundingRect().center().x() # ey = self.endNode.INode.sceneBoundingRect().center().y() # # if the x's or y's are equal offset one slightly to avoid divide by zero errors # if sx == ex: # ex = ex + .001 # if sy == ey: # ey = ey + .001 # self.IRel = RelArc(parent=None, sx=sx, sy=sy, ex=ex, ey=ey, pen=pen, brush=brush, numRels=self.numRels) # METHOD 2 use points on the ellipse # esx, esy, eex, eey = self.calcLine() # self.IRel = RelArc(parent=None, sx=esx, sy=esy, ex=eex, ey=eey, pen=pen, brush=brush, numRels=self.numRels) # METHOD 3 use regularly spaced endpoints on the ellipse # get the centerpoint of the end node cx = self.endNode.INode.sceneBoundingRect().center().x() cy = self.endNode.INode.sceneBoundingRect().center().y() # get the start and end points of the arc esx, esy, eex, eey = self.calcLine2() # create the arc qgraphicsitem self.IRel = RelArc(parent=None, sx=esx, sy=esy, ex=eex, ey=eey, cx=cx, cy=cy, pen=pen, brush=brush, numRels=self.numRels) #create an empty polygon arrowPolygon = QPolygonF() # add arrowhead points arrowPolygon.append(QPointF(self.IRel.b1x, self.IRel.b1y)) arrowPolygon.append(QPointF(eex, eey)) arrowPolygon.append(QPointF(self.IRel.b2x, self.IRel.b2y)) self.arrowHead = QGraphicsPolygonItem(arrowPolygon, parent=None, ) self.arrowHead.setZValue(RELATIONLAYER) self.arrowHead.setBrush(brush) self.arrowHead.setPen(pen) self.arrowHead.setFlag(QGraphicsItem.ItemIsMovable, True) self.arrowHead.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.arrowHead.setFlag(QGraphicsItem.ItemIsSelectable, False) self.arrowHead.setSelected(False) # set data in the RelLine object self.IRel.setData(NODEID, self.relationInstance.NZID) self.IRel.setData(ITEMTYPE, RELINSTANCEARC) # add the RelLine object to the scene self.scene.addItem(self.IRel) # add arrowhead to the scene self.scene.addItem(self.arrowHead) # draw the text self.drawText(self.IRel.mx, self.IRel.my, esx, esy, eex, eey) def drawText(self, mx, my, esx, esy, eex, eey): # mx,my is the center point of the arc # esx,esy is the start point of the arc # eex,eey is the end point of the arc # get the center points of the node qgraphicellipses sx = self.startNode.INode.sceneBoundingRect().center().x() sy = self.startNode.INode.sceneBoundingRect().center().y() sh = self.startNode.INode.sceneBoundingRect().height() ex = self.endNode.INode.sceneBoundingRect().center().x() ey = self.endNode.INode.sceneBoundingRect().center().y() eh = self.endNode.INode.sceneBoundingRect().height() # if the x's or y's are equal offset one slightly to avoid divide by zero errors if sx == ex: ex = ex + .001 if sy == ey: ey = ey + .001 # draw the text # self.IRtext = QGraphicsTextItem(self.relationInstance.relName, parent=None) self.IRtext = RelText(parent=None) # self.IRtext.setZValue(RELATIONLAYER) # self.IRtext.setFlag(QGraphicsItem.ItemIsMovable, True) # self.IRtext.setFlag(QGraphicsItem.ItemIsSelectable, True) # self.IRtext.setSelected(True) # self.IRtext.setAcceptHoverEvents(True) self.IRtext.setData(NODEID, self.relationInstance.NZID) self.IRtext.setData(ITEMTYPE, RELINSTANCETEXT) self.IRtext.setHtml(self.genRelHTML()) #calculate rotation angle adj = abs(esx-eex) opp = abs(esy-eey) OOA = opp/adj rotateAnglerad = (atan(OOA)) rotateAngledeg = degrees(atan(OOA)) # get the height and width of the text graphics item th = self.IRtext.boundingRect().height() tw = self.IRtext.boundingRect().width() # position the relation name text centered on the arc centerpoint if self.startNZID != self.endNZID: # esx, esy, eex, eey if esy >= eey and esx <= eex: # end node is above and to the right self.IRtext.setRotation((360 - rotateAngledeg)) xoffset = (tw/2) * cos(rotateAnglerad) yoffset = (tw/2) * sin(rotateAnglerad) self.IRtext.setPos(QPointF(mx - xoffset, my + yoffset )) elif esy <= eey and esx <= eex: # end node is below and to the right self.IRtext.setRotation(rotateAngledeg) xoffset = (tw/2) * (cos(rotateAnglerad)) yoffset = (tw/2) * (sin(rotateAnglerad)) self.IRtext.setPos(QPointF(mx - xoffset, my - yoffset )) elif esy >= eey and esx >= eex: # end node is above and to the left self.IRtext.setRotation(rotateAngledeg) xoffset = (tw/2) * (cos(rotateAnglerad)) yoffset = (tw/2) * (sin(rotateAnglerad)) self.IRtext.setPos(QPointF(mx - xoffset, my - yoffset )) elif esy <= eey and esx >= eex: # end node is below and to the left self.IRtext.setRotation((360 - rotateAngledeg)) xoffset = (tw/2) * cos(rotateAnglerad) yoffset = (tw/2) * sin(rotateAnglerad) self.IRtext.setPos(QPointF(mx - xoffset, my + yoffset )) # this shouldn't happen else: xoffset = (tw/2) yoffset = (tw/2) self.IRtext.setPos(QPointF(mx, my )) # print("tw {} xoffset {} yoffset {} angle {}".format(tw, xoffset, yoffset, rotateAngledeg)) elif self.startNZID == self.endNZID: if mx > sx: self.IRtext.setPos(QPointF(mx, my - (th) )) if mx < sx: self.IRtext.setPos(QPointF(mx - tw, my - (th) )) else: # this shouldn't happen self.IRtext.setPos(QPointF(mx, my )) self.scene.addItem(self.IRtext) def updateText(self, ): # force the node instance to update its values in case it has been updated from another diagram or the tree view self.relationInstance.reloadDictValues() # self.IRtext.setPlainText(self.relationInstance.relName) self.IRtext.setHtml(self.genRelHTML()) def genRelHTML(self): '''generate html to display the relationship type ''' prefix = '<html><body>' suffix = "</body></html>" myHTML = ('{}<p><font size="1"> [{}]</font></p>{}'.format(prefix, self.relationInstance.relName, suffix)) return myHTML # def calcLine(self, ): # '''calculate the points on the two ellipses to draw a straight line through their centers''' # self.startNodeX = self.startNode.INode.sceneBoundingRect().center().x() # self.startNodeY = self.startNode.INode.sceneBoundingRect().center().y() # self.endNodeX = self.endNode.INode.sceneBoundingRect().center().x() # self.endNodeY = self.endNode.INode.sceneBoundingRect().center().y() # # self.distanceX = abs(self.startNodeX - self.endNodeX) + .001 # self.distanceY = abs(self.startNodeY - self.endNodeY) + .001 # temp = (pow(self.distanceX,2) + pow(self.distanceY,2)) - (2 * self.distanceX * self.distanceY * cos(radians(90))) # self.distanceXY = sqrt(temp) # a = self.distanceX # b = self.distanceY # c = self.distanceXY ## angA = angle(a,b,c) ## angB = angle(b,c,a) # angC = angleDegrees(c,a,b) # # if self.endNodeX == self.startNodeX: # self.endNodeX = self.endNodeX + .001 # if self.endNodeY == self.startNodeY: # self.endNodeY = self.endNodeY + .001 # # if self.endNodeX > self.startNodeX and self.endNodeY > self.startNodeY: # startangle = angC # endangle = 180 + angC # elif self.endNodeX < self.startNodeX and self.endNodeY > self.startNodeY: # startangle = 180 - angC # endangle = 360 - angC # elif self.endNodeX < self.startNodeX and self.endNodeY < self.startNodeY: # startangle = 180 + angC # endangle = angC # elif self.endNodeX > self.startNodeX and self.endNodeY < self.startNodeY: # startangle = 360 - angC # endangle = 180 - angC # # #print("angA: {} angleB: {} angleC: {} startangle: {}".format(angA, angB, angC, startangle)) # aa = self.startNode.INode.boundingRect().width()/2.0 # bb = self.startNode.INode.boundingRect().height()/2.0 # sn = Ellipse(self.startNodeX, self.startNodeY, aa, bb) # sx, sy = sn.pointFromAngle(radians(startangle)) # cc = self.endNode.INode.boundingRect().width()/2.0 # dd = self.endNode.INode.boundingRect().height()/2.0 # en = Ellipse(self.endNodeX, self.endNodeY, cc, dd) #need to calc width/height of end node. # ex, ey = en.pointFromAngle(radians(endangle)) # #print("sx {} - sy {} - ex {} - ey {}".format(sx,sy,ex,sy)) # return sx, sy, ex, ey def calcLine2(self, ): '''calculate the point on the start and end node ellipse for an arc ''' # get centerpoints of the two nodes self.startNodeX = self.startNode.INode.sceneBoundingRect().center().x() self.startNodeY = self.startNode.INode.sceneBoundingRect().center().y() self.endNodeX = self.endNode.INode.sceneBoundingRect().center().x() self.endNodeY = self.endNode.INode.sceneBoundingRect().center().y() self.distanceX = abs(self.startNodeX - self.endNodeX) + .001 self.distanceY = abs(self.startNodeY - self.endNodeY) + .001 temp = (pow(self.distanceX,2) + pow(self.distanceY,2)) - (2 * self.distanceX * self.distanceY * cos(radians(90))) self.distanceXY = sqrt(temp) a = self.distanceX b = self.distanceY c = self.distanceXY # angA = angle(a,b,c) # angB = angle(b,c,a) angC = angleDegrees(c,a,b) # print("angC {}".format(angC)) if self.endNodeX == self.startNodeX: self.endNodeX = self.endNodeX + .001 if self.endNodeY == self.startNodeY: self.endNodeY = self.endNodeY + .001 # adjust starting and ending points based on the number of rels between the node, if more than 7 in the same direction just start stacking them one on top of the other. if self.numRels > 6: adjustDegree = (7) * 10 else: adjustDegree = (self.numRels+1) * 10 if self.endNodeX > self.startNodeX and self.endNodeY > self.startNodeY: startangle = angC - adjustDegree endangle = 180 + angC + adjustDegree elif self.endNodeX < self.startNodeX and self.endNodeY > self.startNodeY: startangle = 180 - angC - adjustDegree endangle = 360 - angC + adjustDegree elif self.endNodeX < self.startNodeX and self.endNodeY < self.startNodeY: startangle = 180 + angC - adjustDegree endangle = angC + adjustDegree elif self.endNodeX > self.startNodeX and self.endNodeY < self.startNodeY: startangle = 360 - angC - adjustDegree endangle = 180 - angC + adjustDegree # print("adjust: {}startangle: {} endangle: {}".format(adjustDegree, startangle, endangle)) aa = self.startNode.INode.boundingRect().width()/2.0 bb = self.startNode.INode.boundingRect().height()/2.0 sn = Ellipse(self.startNodeX, self.startNodeY, aa, bb) sx, sy = sn.pointFromAngle(radians(startangle)) cc = self.endNode.INode.boundingRect().width()/2.0 dd = self.endNode.INode.boundingRect().height()/2.0 en = Ellipse(self.endNodeX, self.endNodeY, cc, dd) #need to calc width/height of end node. ex, ey = en.pointFromAngle(radians(endangle)) #print("sx {} - sy {} - ex {} - ey {}".format(sx,sy,ex,sy)) return sx, sy, ex, ey def calcLine3(self, ): '''calculate the point on the start and end node ellipse for a straight line ''' # get centerpoints of the two nodes self.startNodeX = self.startNode.INode.sceneBoundingRect().center().x() self.startNodeY = self.startNode.INode.sceneBoundingRect().center().y() self.endNodeX = self.endNode.INode.sceneBoundingRect().center().x() self.endNodeY = self.endNode.INode.sceneBoundingRect().center().y() self.distanceX = abs(self.startNodeX - self.endNodeX) + .001 self.distanceY = abs(self.startNodeY - self.endNodeY) + .001 temp = (pow(self.distanceX,2) + pow(self.distanceY,2)) - (2 * self.distanceX * self.distanceY * cos(radians(90))) self.distanceXY = sqrt(temp) a = self.distanceX b = self.distanceY c = self.distanceXY # angA = angle(a,b,c) # angB = angle(b,c,a) angC = angleDegrees(c,a,b) # print("angC {}".format(angC)) if self.endNodeX == self.startNodeX: self.endNodeX = self.endNodeX + .001 if self.endNodeY == self.startNodeY: self.endNodeY = self.endNodeY + .001 # # adjust starting and ending points based on the number of rels between the node, if more than 7 in the same direction just start stacking them one on top of the other. # if self.numRels > 6: # adjustDegree = (7) * 10 # else: # adjustDegree = (self.numRels+1) * 10 adjustDegree = 0 if self.endNodeX > self.startNodeX and self.endNodeY > self.startNodeY: startangle = angC - adjustDegree endangle = 180 + angC + adjustDegree elif self.endNodeX < self.startNodeX and self.endNodeY > self.startNodeY: startangle = 180 - angC - adjustDegree endangle = 360 - angC + adjustDegree elif self.endNodeX < self.startNodeX and self.endNodeY < self.startNodeY: startangle = 180 + angC - adjustDegree endangle = angC + adjustDegree elif self.endNodeX > self.startNodeX and self.endNodeY < self.startNodeY: startangle = 360 - angC - adjustDegree endangle = 180 - angC + adjustDegree # print("adjust: {}startangle: {} endangle: {}".format(adjustDegree, startangle, endangle)) aa = self.startNode.INode.boundingRect().width()/2.0 bb = self.startNode.INode.boundingRect().height()/2.0 sn = Ellipse(self.startNodeX, self.startNodeY, aa, bb) sx, sy = sn.pointFromAngle(radians(startangle)) cc = self.endNode.INode.boundingRect().width()/2.0 dd = self.endNode.INode.boundingRect().height()/2.0 en = Ellipse(self.endNodeX, self.endNodeY, cc, dd) #need to calc width/height of end node. ex, ey = en.pointFromAngle(radians(endangle)) #print("sx {} - sy {} - ex {} - ey {}".format(sx,sy,ex,sy)) return sx, sy, ex, ey # def moveRelationshipLine(self, ): # self.drawRelationship() def getObjectDict(self, ): objectDict = {} objectDict["NZID"] = self.relationInstance.NZID objectDict["diagramType"] = self.diagramType return objectDict
class EdgeItem(GraphItem): _qt_pen_styles = { 'dashed': Qt.DashLine, 'dotted': Qt.DotLine, 'solid': Qt.SolidLine, } def __init__(self, highlight_level, spline, label_center, label, from_node, to_node, parent=None, penwidth=1, edge_color=None, style='solid'): super(EdgeItem, self).__init__(highlight_level, parent) self.from_node = from_node self.from_node.add_outgoing_edge(self) self.to_node = to_node self.to_node.add_incoming_edge(self) self._default_edge_color = self._COLOR_BLACK if edge_color is not None: self._default_edge_color = edge_color self._default_text_color = self._COLOR_BLACK self._default_color = self._COLOR_BLACK self._text_brush = QBrush(self._default_color) self._shape_brush = QBrush(self._default_color) if style in ['dashed', 'dotted']: self._shape_brush = QBrush(Qt.transparent) self._label_pen = QPen() self._label_pen.setColor(self._default_text_color) self._label_pen.setJoinStyle(Qt.RoundJoin) self._edge_pen = QPen(self._label_pen) self._edge_pen.setWidth(penwidth) self._edge_pen.setColor(self._default_edge_color) self._edge_pen.setStyle(self._qt_pen_styles.get(style, Qt.SolidLine)) self._sibling_edges = set() self._label = None if label is not None: self._label = QGraphicsSimpleTextItem(label) self._label.setFont(GraphItem._LABEL_FONT) label_rect = self._label.boundingRect() label_rect.moveCenter(label_center) self._label.setPos(label_rect.x(), label_rect.y()) self._label.hoverEnterEvent = self._handle_hoverEnterEvent self._label.hoverLeaveEvent = self._handle_hoverLeaveEvent self._label.setAcceptHoverEvents(True) # spline specification according to # http://www.graphviz.org/doc/info/attrs.html#k:splineType coordinates = spline.split(' ') # extract optional end_point end_point = None if (coordinates[0].startswith('e,')): parts = coordinates.pop(0)[2:].split(',') end_point = QPointF(float(parts[0]), -float(parts[1])) # extract optional start_point if (coordinates[0].startswith('s,')): parts = coordinates.pop(0).split(',') # first point parts = coordinates.pop(0).split(',') point = QPointF(float(parts[0]), -float(parts[1])) path = QPainterPath(point) while len(coordinates) > 2: # extract triple of points for a cubic spline parts = coordinates.pop(0).split(',') point1 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point2 = QPointF(float(parts[0]), -float(parts[1])) parts = coordinates.pop(0).split(',') point3 = QPointF(float(parts[0]), -float(parts[1])) path.cubicTo(point1, point2, point3) self._arrow = None if end_point is not None: # draw arrow self._arrow = QGraphicsPolygonItem() polygon = QPolygonF() polygon.append(point3) offset = QPointF(end_point - point3) corner1 = QPointF(-offset.y(), offset.x()) * 0.35 corner2 = QPointF(offset.y(), -offset.x()) * 0.35 polygon.append(point3 + corner1) polygon.append(end_point) polygon.append(point3 + corner2) self._arrow.setPolygon(polygon) self._arrow.hoverEnterEvent = self._handle_hoverEnterEvent self._arrow.hoverLeaveEvent = self._handle_hoverLeaveEvent self._arrow.setAcceptHoverEvents(True) self._path = QGraphicsPathItem(parent) self._path.setPath(path) self.addToGroup(self._path) self.set_node_color() self.set_label_color() def add_to_scene(self, scene): scene.addItem(self) if self._label is not None: scene.addItem(self._label) if self._arrow is not None: scene.addItem(self._arrow) def setToolTip(self, tool_tip): super(EdgeItem, self).setToolTip(tool_tip) if self._label is not None: self._label.setToolTip(tool_tip) if self._arrow is not None: self._arrow.setToolTip(tool_tip) def add_sibling_edge(self, edge): self._sibling_edges.add(edge) def set_node_color(self, color=None): if color is None: self._label_pen.setColor(self._default_text_color) self._text_brush.setColor(self._default_color) if self._shape_brush.isOpaque(): self._shape_brush.setColor(self._default_edge_color) self._edge_pen.setColor(self._default_edge_color) else: self._label_pen.setColor(color) self._text_brush.setColor(color) if self._shape_brush.isOpaque(): self._shape_brush.setColor(color) self._edge_pen.setColor(color) self._path.setPen(self._edge_pen) if self._arrow is not None: self._arrow.setBrush(self._shape_brush) self._arrow.setPen(self._edge_pen) def set_label_color(self, color=None): if color is None: self._label_pen.setColor(self._default_text_color) else: self._label_pen.setColor(color) if self._label is not None: self._label.setBrush(self._text_brush) self._label.setPen(self._label_pen) def _handle_hoverEnterEvent(self, event): # hovered edge item in red self.set_node_color(self._COLOR_RED) self.set_label_color(self._COLOR_RED) if self._highlight_level > 1: if self.from_node != self.to_node: # from-node in blue self.from_node.set_node_color(self._COLOR_BLUE) # to-node in green self.to_node.set_node_color(self._COLOR_GREEN) else: # from-node/in-node in teal self.from_node.set_node_color(self._COLOR_TEAL) self.to_node.set_node_color(self._COLOR_TEAL) if self._highlight_level > 2: # sibling edges in orange for sibling_edge in self._sibling_edges: sibling_edge.set_node_color(self._COLOR_ORANGE) def _handle_hoverLeaveEvent(self, event): self.set_node_color() self.set_label_color() if self._highlight_level > 1: self.from_node.set_node_color() self.to_node.set_node_color() if self._highlight_level > 2: for sibling_edge in self._sibling_edges: sibling_edge.set_node_color()
class CallOut(): ''' This represents a callouton the diagram This class creates a text item and then surrounds it with a polygon that is a rectangle with a pointer to another object on the diagram. This can be used by hover over functions or be displayed as a part of a node or relationship ''' def __init__(self, scene, text, anchorPoint, diagramType, format): self.scene = scene self.model = self.scene.parent.model self.text = text self.anchorPoint = anchorPoint self.diagramType = diagramType self.format = format # initialize the two qgraphicsitems needed to draw a relationship to None self.itemText = None self.itemPolygon = None self.drawIt def name(self, ): return "no name" def NZID(self, ): return None def clearItem(self, ): if (not self.itemText is None and not self.itemText.scene() is None): self.itemText.scene().removeItem(self.itemText) if (not self.itemPolygon is None and not self.itemPolygon.scene() is None): self.itemPolygon.scene().removeItem(self.itemPolygon) def drawIt(self, ): ''' draw the callout ''' # if the polygon and text graphics items already exist on the scene then delete them self.clearItem() # draw the relationship arc pen = self.format.pen() brush = self.format.brush() # create text box # draw the text self.itemText = QGraphicsTextItem(self.relationInstance.relName, parent=None) self.itemText.setZValue(CALLOUTLAYER) self.itemText.setFlag(QGraphicsItem.ItemIsMovable, True) self.itemText.setFlag(QGraphicsItem.ItemIsSelectable, True) self.itemText.setSelected(False) self.itemText.setData(NODEID, self.relationInstance.NZID) self.itemText.setData(ITEMTYPE, CALLOUT) self.itemText.setHtml(self.genTextHTML()) # set the position of the text self.itemText.setPos(self.anchorPoint) # get the height and width of the text graphics item th = self.IRtext.boundingRect().height() tw = self.IRtext.boundingRect().width() #create an empty polygon arrowPolygon = QPolygonF() # add callout points arrowPolygon.append(self.anchorPoint) arrowPolygon.append( QPointF(self.anchorPoint.x() + tw, self.anchorPoint.y())) arrowPolygon.append( QPointF(self.anchorPoint.x() + tw, self.anchorPoint.y())) arrowPolygon.append( QPointF(self.anchorPoint.x() + tw, self.anchorPoint.y() + th)) arrowPolygon.append( QPointF(self.anchorPoint.x(), self.anchorPoint.y() + th)) self.itemPolygon = QGraphicsPolygonItem( arrowPolygon, parent=None, ) self.itemPolygon.setZValue(CALLOUTLAYER) self.itemPolygon.setBrush(brush) self.itemPolygon.setPen(pen) self.itemPolygon.setFlag(QGraphicsItem.ItemIsMovable, True) self.itemPolygon.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.itemPolygon.setFlag(QGraphicsItem.ItemIsSelectable, False) self.itemPolygon.setSelected(False) # set data in the RelLine object self.IRel.setData(NODEID, self.relationInstance.NZID) self.IRel.setData(ITEMTYPE, RELINSTANCEARC) # add the polygon object to the scene self.scene.addItem(self.itemPolygon) # add text to the scene self.scene.addItem(self.itemText) def updateText(self, ): # # force the node instance to update its values in case it has been updated from another diagram or the tree view # self.relationInstance.reloadDictValues() # self.IRtext.setPlainText(self.relationInstance.relName) self.itemText.setHtml(self.genTextHTML()) def genTextHTML(self): '''generate html to display the text ''' prefix = '<html><body>' suffix = "</body></html>" myHTML = ('{}<p><font size="1"> [{}]</font></p>{}'.format( prefix, self.text, suffix)) return myHTML def moveIt(self, ): self.drawIt()
class VesselPositionSystem(QDialog, Ui_VesselPosSystem): def __init__(self, config, parent=None): super(VesselPositionSystem, self).__init__(parent) self.setupUi(self) self.setWindowTitle("Vessel Position System") self.config = config # Set maximum and minimum values self.vrp_x_offset_doubleSpinBox.setMaximum(500.0) self.vrp_y_offset_doubleSpinBox.setMaximum(500.0) self.gps_x_offset_doubleSpinBox.setMaximum(500.0) self.gps_y_offset_doubleSpinBox.setMaximum(500.0) self.vrp_x_offset_doubleSpinBox.setMinimum(-500.0) self.vrp_y_offset_doubleSpinBox.setMinimum(-500.0) self.gps_y_offset_doubleSpinBox.setMinimum(-500.0) self.gps_x_offset_doubleSpinBox.setMinimum(-500.0) self.vessel_length_doubleSpinBox.setMinimum(1.0) self.vessel_width_doubleSpinBox.setMinimum(1.0) # set config values self.set_spinbox_value(self.vessel_length_doubleSpinBox, "vessel_length") self.set_spinbox_value(self.vessel_width_doubleSpinBox, "vessel_width") self.set_spinbox_value(self.vrp_x_offset_doubleSpinBox, 'vrp_offset_x') self.set_spinbox_value(self.vrp_y_offset_doubleSpinBox, 'vrp_offset_y') self.set_spinbox_value(self.gps_x_offset_doubleSpinBox, 'gps_offset_x') self.set_spinbox_value(self.gps_y_offset_doubleSpinBox, 'gps_offset_y') self.set_spinbox_value(self.gps_heading_doubleSpinBox, 'gps_offset_heading') # connect spinbox self.vessel_length_doubleSpinBox.valueChanged.connect( self.print_vessel) self.vessel_width_doubleSpinBox.valueChanged.connect(self.print_vessel) self.vrp_x_offset_doubleSpinBox.valueChanged.connect(self.print_vessel) self.vrp_y_offset_doubleSpinBox.valueChanged.connect(self.print_vessel) self.gps_x_offset_doubleSpinBox.valueChanged.connect(self.print_vessel) self.gps_y_offset_doubleSpinBox.valueChanged.connect(self.print_vessel) self.gps_heading_doubleSpinBox.valueChanged.connect(self.print_vessel) if util.find_spec('usblcontroller') is not None: self.usbl_x_offset_doubleSpinBox.setMaximum(500.0) self.usbl_x_offset_doubleSpinBox.setMinimum(-500.0) self.set_spinbox_value(self.usbl_x_offset_doubleSpinBox, 'usbl_offset_x') self.usbl_y_offset_doubleSpinBox.setMaximum(500.0) self.usbl_y_offset_doubleSpinBox.setMinimum(-500.0) self.set_spinbox_value(self.usbl_y_offset_doubleSpinBox, 'usbl_offset_y') self.set_spinbox_value(self.usbl_z_offset_doubleSpinBox, 'usbl_offset_z') self.set_spinbox_value(self.usbl_heading_doubleSpinBox, 'usbl_offset_heading') self.usbl_x_offset_doubleSpinBox.valueChanged.connect( self.print_vessel) self.usbl_y_offset_doubleSpinBox.valueChanged.connect( self.print_vessel) self.usbl_z_offset_doubleSpinBox.valueChanged.connect( self.print_vessel) self.usbl_heading_doubleSpinBox.valueChanged.connect( self.print_vessel) else: self.hide_widgets_on_layout(self.usbl_gridLayout) # connect accept button self.buttonBox.accepted.connect(self.on_accept) # set top scene self.top_scene = QGraphicsScene(self.top_graphicsView) self.top_graphicsView.setScene(self.top_scene) self.side_scene = QGraphicsScene(self.side_graphicsView) self.side_graphicsView.setScene(self.side_scene) def hide_widgets_on_layout(self, layout): """ Hide all widgets from layout :param layout: a layout """ for i in reversed(range(layout.count())): item = layout.takeAt(i) widget = item.widget() if widget is not None: widget.hide() else: self.hide_elements(item.layout()) def set_spinbox_value(self, spinbox, value): try: spinbox.setValue(self.config.csettings[value]) except: spinbox.setValue(0.0) def print_vessel(self): """ printvessel draw vessel, gps, usbl and vessel reference point on a qgraphicsscene """ self.print_top_view() self.print_side_view() def print_top_view(self): """ draw draw vessel, gps, usbl and vessel reference point on a top_graphicsView """ # clear previous scene self.top_scene.clear() self.top_graphicsView.viewport().update() # get vessel spinbox values v_width = self.vessel_width_doubleSpinBox.value() v_length = self.vessel_length_doubleSpinBox.value() vrp_x_on_vessel = self.vrp_x_offset_doubleSpinBox.value() vrp_y_on_vessel = self.vrp_y_offset_doubleSpinBox.value() gps_x_on_vessel = self.gps_x_offset_doubleSpinBox.value() gps_y_on_vessel = self.gps_y_offset_doubleSpinBox.value() if util.find_spec('usblcontroller') is not None: usbl_x_on_vessel = self.usbl_x_offset_doubleSpinBox.value() usbl_y_on_vessel = self.usbl_y_offset_doubleSpinBox.value() else: usbl_x_on_vessel = 0 usbl_y_on_vessel = 0 # get width and height from view w_max = self.top_graphicsView.width() h_max = self.top_graphicsView.height() # set max if v_width > v_length: max_pix = v_width else: max_pix = v_length # set pixel ratio if w_max < h_max: pix_ratio = (w_max - 20) / max_pix else: pix_ratio = (h_max - 20) / max_pix # set the size of the vessel vessel = QPolygonF([ QPointF(pix_ratio * v_width / 2, 0), QPointF(pix_ratio * v_width, pix_ratio * v_length / 4), QPointF(pix_ratio * v_width, pix_ratio * v_length), QPointF(0, pix_ratio * v_length), QPointF(0, pix_ratio * v_length / 4) ]) self.item = QGraphicsPolygonItem(vessel) # set brown color self.item.setBrush(QColor(210, 180, 140)) x_origin_scene = (pix_ratio * v_width / 2) y_origin_scene = (pix_ratio * v_length / 2) # coordinate system line_x_coord = QGraphicsLineItem(x_origin_scene, 0, x_origin_scene, y_origin_scene) line_y_coord = QGraphicsLineItem(x_origin_scene, y_origin_scene, pix_ratio * v_width, y_origin_scene) x_label = QGraphicsSimpleTextItem("X", line_x_coord) x_label.setPos(x_origin_scene - 10, 0 + 10) y_label = QGraphicsSimpleTextItem("Y", line_y_coord) y_label.setPos(pix_ratio * v_width - 20, y_origin_scene) x_origin_scene += vrp_y_on_vessel * pix_ratio y_origin_scene += -vrp_x_on_vessel * pix_ratio # draw origin point origin = QGraphicsEllipseItem(x_origin_scene - 10, y_origin_scene - 10, 20, 20) origin.setBrush(Qt.white) line_one_origin = QGraphicsLineItem(x_origin_scene - 10, y_origin_scene, x_origin_scene + 10, y_origin_scene) line_two_origin = QGraphicsLineItem(x_origin_scene, y_origin_scene - 10, x_origin_scene, y_origin_scene + 10) # gps position gps_circle = QGraphicsEllipseItem( x_origin_scene - 10 + gps_y_on_vessel * pix_ratio, y_origin_scene - 10 - gps_x_on_vessel * pix_ratio, 20, 20) gps_circle.setBrush(QColor(143, 188, 143)) line_one_gps = QGraphicsLineItem( x_origin_scene - 10 + gps_y_on_vessel * pix_ratio, y_origin_scene - gps_x_on_vessel * pix_ratio, x_origin_scene + 10 + gps_y_on_vessel * pix_ratio, y_origin_scene - gps_x_on_vessel * pix_ratio) line_two_gps = QGraphicsLineItem( x_origin_scene + gps_y_on_vessel * pix_ratio, y_origin_scene - 10 - gps_x_on_vessel * pix_ratio, x_origin_scene + gps_y_on_vessel * pix_ratio, y_origin_scene + 10 - gps_x_on_vessel * pix_ratio) # gps label gps_label = QGraphicsSimpleTextItem("GPS", gps_circle) gps_label.setPos(x_origin_scene - 10 + gps_y_on_vessel * pix_ratio, y_origin_scene + 10 - gps_x_on_vessel * pix_ratio) if util.find_spec('usblcontroller') is not None: # usbl position usbl_circle = QGraphicsEllipseItem( x_origin_scene - 10 + usbl_y_on_vessel * pix_ratio, y_origin_scene - 10 - usbl_x_on_vessel * pix_ratio, 20, 20) usbl_circle.setBrush(QColor(255, 99, 71)) line_one_usbl = QGraphicsLineItem( x_origin_scene - 10 + usbl_y_on_vessel * pix_ratio, y_origin_scene - usbl_x_on_vessel * pix_ratio, x_origin_scene + 10 + usbl_y_on_vessel * pix_ratio, y_origin_scene - usbl_x_on_vessel * pix_ratio) line_two_usbl = QGraphicsLineItem( x_origin_scene + usbl_y_on_vessel * pix_ratio, y_origin_scene - 10 - usbl_x_on_vessel * pix_ratio, x_origin_scene + usbl_y_on_vessel * pix_ratio, y_origin_scene + 10 - usbl_x_on_vessel * pix_ratio) # usbl label usbl_label = QGraphicsSimpleTextItem("USBL", usbl_circle) if usbl_x_on_vessel == gps_x_on_vessel and usbl_y_on_vessel == gps_y_on_vessel: usbl_label.setPos( x_origin_scene - 10 + usbl_y_on_vessel * pix_ratio, y_origin_scene - 30 - usbl_x_on_vessel * pix_ratio) else: usbl_label.setPos( x_origin_scene - 10 + usbl_y_on_vessel * pix_ratio, y_origin_scene + 10 - usbl_x_on_vessel * pix_ratio) origin_label = QGraphicsSimpleTextItem("VRP", origin) if (usbl_x_on_vessel == 0 and usbl_y_on_vessel == 0) or (gps_x_on_vessel == 0 and gps_y_on_vessel == 0): origin_label.setPos(x_origin_scene + 10, y_origin_scene - 10) else: origin_label.setPos(x_origin_scene - 10, y_origin_scene + 10) # fit view/scene self.top_graphicsView.setSceneRect(0, 0, pix_ratio * v_width, pix_ratio * v_length) # add vessel to the scene self.top_graphicsView.scene().addItem(self.item) # add origin to the scene self.top_graphicsView.scene().addItem(origin) self.top_graphicsView.scene().addItem(line_one_origin) self.top_graphicsView.scene().addItem(line_two_origin) # add gps self.top_graphicsView.scene().addItem(gps_circle) self.top_graphicsView.scene().addItem(line_one_gps) self.top_graphicsView.scene().addItem(line_two_gps) if util.find_spec('usblcontroller') is not None: # add usbl self.top_graphicsView.scene().addItem(usbl_circle) self.top_graphicsView.scene().addItem(line_one_usbl) self.top_graphicsView.scene().addItem(line_two_usbl) # add coord system self.top_graphicsView.scene().addItem(line_x_coord) self.top_graphicsView.scene().addItem(line_y_coord) # set background self.top_scene.setBackgroundBrush(QColor(204, 229, 255)) # set antialiasing renderhint self.top_graphicsView.setRenderHint(QPainter.Antialiasing) def print_side_view(self): """ draw vessel, usbl and vessel reference point on a side_graphicsView """ # clear previous scene self.side_scene.clear() self.side_graphicsView.viewport().update() # get vessel spinbox values v_length = self.vessel_length_doubleSpinBox.value() v_height = v_length / 3 vrp_x_on_vessel = self.vrp_x_offset_doubleSpinBox.value() if util.find_spec('usblcontroller') is not None: usbl_x_on_vessel = self.usbl_x_offset_doubleSpinBox.value() usbl_z_on_vessel = self.usbl_z_offset_doubleSpinBox.value() else: usbl_x_on_vessel = 0 usbl_z_on_vessel = 0 # get width and height from view w_max = self.side_graphicsView.width() h_max = self.side_graphicsView.height() # set max if v_height > v_length: max_pix = v_height else: max_pix = v_length # set pixel ratio if w_max < h_max: pix_ratio = (w_max - 20) / max_pix else: pix_ratio = (h_max - 20) / max_pix # set the size of the vessel vessel = QPolygonF([ QPointF(0, 0), QPointF(pix_ratio * v_length, 0), QPointF(pix_ratio * v_length * 3 / 4, pix_ratio * v_height), QPointF(0, pix_ratio * v_height) ]) self.item = QGraphicsPolygonItem(vessel) # set brown color self.item.setBrush(QColor(210, 180, 140)) x_origin_scene = (pix_ratio * v_length / 2) y_origin_scene = (pix_ratio * v_height / 2) # coordinate system line_x_coord = QGraphicsLineItem( x_origin_scene, y_origin_scene, pix_ratio * v_length - (pix_ratio * v_length - pix_ratio * v_length * 3 / 4) / 2, y_origin_scene) line_z_coord = QGraphicsLineItem(x_origin_scene, y_origin_scene, x_origin_scene, pix_ratio * v_height) x_label = QGraphicsSimpleTextItem("X", line_x_coord) x_label.setPos( pix_ratio * v_length - (pix_ratio * v_length - pix_ratio * v_length * 3 / 4) / 2 - 30, y_origin_scene) z_label = QGraphicsSimpleTextItem("Z", line_z_coord) z_label.setPos(x_origin_scene - 20, pix_ratio * v_height - 20) # set sea background sea_polygon = QPolygonF([ QPointF(-w_max, y_origin_scene), QPointF(w_max, y_origin_scene), QPointF(x_origin_scene + w_max, h_max + usbl_z_on_vessel * pix_ratio), QPointF(-w_max, h_max + usbl_z_on_vessel * pix_ratio) ]) sea = QGraphicsPolygonItem(sea_polygon) sea.setBrush(QColor(204, 229, 255)) x_origin_scene += vrp_x_on_vessel * pix_ratio # draw origin point origin = QGraphicsEllipseItem(x_origin_scene - 10, y_origin_scene - 10, 20, 20) origin.setBrush(Qt.white) line_one_origin = QGraphicsLineItem(x_origin_scene - 10, y_origin_scene, x_origin_scene + 10, y_origin_scene) line_two_origin = QGraphicsLineItem(x_origin_scene, y_origin_scene - 10, x_origin_scene, y_origin_scene + 10) if util.find_spec('usblcontroller') is not None: # usbl position usbl_circle = QGraphicsEllipseItem( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene - 10 + usbl_z_on_vessel * pix_ratio, 20, 20) usbl_circle.setBrush(QColor(255, 99, 71)) line_one_usbl = QGraphicsLineItem( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + usbl_z_on_vessel * pix_ratio, x_origin_scene + 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + usbl_z_on_vessel * pix_ratio) line_two_usbl = QGraphicsLineItem( x_origin_scene + usbl_x_on_vessel * pix_ratio, y_origin_scene - 10 + usbl_z_on_vessel * pix_ratio, x_origin_scene + usbl_x_on_vessel * pix_ratio, y_origin_scene + 10 + usbl_z_on_vessel * pix_ratio) # define labels usbl_label = QGraphicsSimpleTextItem("USBL", usbl_circle) usbl_label.setPos( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + 10 + usbl_z_on_vessel * pix_ratio) origin_label = QGraphicsSimpleTextItem("VRP", origin) if usbl_x_on_vessel == 0 and usbl_z_on_vessel == 0: origin_label.setPos(x_origin_scene + 10, y_origin_scene - 10) else: origin_label.setPos(x_origin_scene - 10, y_origin_scene + 10) # fit view/scene self.side_scene.setSceneRect( 0, 0, pix_ratio * v_length, pix_ratio * v_height + usbl_z_on_vessel * pix_ratio) self.side_graphicsView.scene().addItem(sea) # add vessel to the scene self.side_graphicsView.scene().addItem(self.item) # add origin to the scene self.side_graphicsView.scene().addItem(origin) self.side_graphicsView.scene().addItem(line_one_origin) self.side_graphicsView.scene().addItem(line_two_origin) if util.find_spec('usblcontroller') is not None: # add usbl self.side_graphicsView.scene().addItem(usbl_circle) self.side_graphicsView.scene().addItem(line_one_usbl) self.side_graphicsView.scene().addItem(line_two_usbl) # add coord system self.side_graphicsView.scene().addItem(line_x_coord) self.side_graphicsView.scene().addItem(line_z_coord) # set background self.side_scene.setBackgroundBrush(Qt.white) # set antialiasing renderhint self.side_graphicsView.setRenderHint(QPainter.Antialiasing) def on_accept(self): """On accept set values on config csettings""" self.config.csettings[ "vessel_width"] = self.vessel_width_doubleSpinBox.value() self.config.csettings[ "vessel_length"] = self.vessel_length_doubleSpinBox.value() self.config.csettings[ "vrp_offset_x"] = self.vrp_x_offset_doubleSpinBox.value() self.config.csettings[ "vrp_offset_y"] = self.vrp_y_offset_doubleSpinBox.value() self.config.csettings[ 'gps_offset_x'] = self.gps_x_offset_doubleSpinBox.value() self.config.csettings[ 'gps_offset_y'] = self.gps_y_offset_doubleSpinBox.value() self.config.csettings[ 'gps_offset_heading'] = self.gps_heading_doubleSpinBox.value() if util.find_spec('usblcontroller') is not None: self.config.csettings[ 'usbl_offset_x'] = self.usbl_x_offset_doubleSpinBox.value() self.config.csettings[ 'usbl_offset_y'] = self.usbl_y_offset_doubleSpinBox.value() self.config.csettings[ 'usbl_offset_z'] = self.usbl_z_offset_doubleSpinBox.value() self.config.csettings[ 'usbl_offset_heading'] = self.usbl_heading_doubleSpinBox.value( ) self.config.save() def resizeEvent(self, qresizeevent): super(VesselPositionSystem, self).resizeEvent(qresizeevent) self.print_vessel()
def print_side_view(self): """ draw vessel, usbl and vessel reference point on a side_graphicsView """ # clear previous scene self.side_scene.clear() self.side_graphicsView.viewport().update() # get vessel spinbox values v_length = self.vessel_length_doubleSpinBox.value() v_height = v_length / 3 vrp_x_on_vessel = self.vrp_x_offset_doubleSpinBox.value() if util.find_spec('usblcontroller') is not None: usbl_x_on_vessel = self.usbl_x_offset_doubleSpinBox.value() usbl_z_on_vessel = self.usbl_z_offset_doubleSpinBox.value() else: usbl_x_on_vessel = 0 usbl_z_on_vessel = 0 # get width and height from view w_max = self.side_graphicsView.width() h_max = self.side_graphicsView.height() # set max if v_height > v_length: max_pix = v_height else: max_pix = v_length # set pixel ratio if w_max < h_max: pix_ratio = (w_max - 20) / max_pix else: pix_ratio = (h_max - 20) / max_pix # set the size of the vessel vessel = QPolygonF([ QPointF(0, 0), QPointF(pix_ratio * v_length, 0), QPointF(pix_ratio * v_length * 3 / 4, pix_ratio * v_height), QPointF(0, pix_ratio * v_height) ]) self.item = QGraphicsPolygonItem(vessel) # set brown color self.item.setBrush(QColor(210, 180, 140)) x_origin_scene = (pix_ratio * v_length / 2) y_origin_scene = (pix_ratio * v_height / 2) # coordinate system line_x_coord = QGraphicsLineItem( x_origin_scene, y_origin_scene, pix_ratio * v_length - (pix_ratio * v_length - pix_ratio * v_length * 3 / 4) / 2, y_origin_scene) line_z_coord = QGraphicsLineItem(x_origin_scene, y_origin_scene, x_origin_scene, pix_ratio * v_height) x_label = QGraphicsSimpleTextItem("X", line_x_coord) x_label.setPos( pix_ratio * v_length - (pix_ratio * v_length - pix_ratio * v_length * 3 / 4) / 2 - 30, y_origin_scene) z_label = QGraphicsSimpleTextItem("Z", line_z_coord) z_label.setPos(x_origin_scene - 20, pix_ratio * v_height - 20) # set sea background sea_polygon = QPolygonF([ QPointF(-w_max, y_origin_scene), QPointF(w_max, y_origin_scene), QPointF(x_origin_scene + w_max, h_max + usbl_z_on_vessel * pix_ratio), QPointF(-w_max, h_max + usbl_z_on_vessel * pix_ratio) ]) sea = QGraphicsPolygonItem(sea_polygon) sea.setBrush(QColor(204, 229, 255)) x_origin_scene += vrp_x_on_vessel * pix_ratio # draw origin point origin = QGraphicsEllipseItem(x_origin_scene - 10, y_origin_scene - 10, 20, 20) origin.setBrush(Qt.white) line_one_origin = QGraphicsLineItem(x_origin_scene - 10, y_origin_scene, x_origin_scene + 10, y_origin_scene) line_two_origin = QGraphicsLineItem(x_origin_scene, y_origin_scene - 10, x_origin_scene, y_origin_scene + 10) if util.find_spec('usblcontroller') is not None: # usbl position usbl_circle = QGraphicsEllipseItem( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene - 10 + usbl_z_on_vessel * pix_ratio, 20, 20) usbl_circle.setBrush(QColor(255, 99, 71)) line_one_usbl = QGraphicsLineItem( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + usbl_z_on_vessel * pix_ratio, x_origin_scene + 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + usbl_z_on_vessel * pix_ratio) line_two_usbl = QGraphicsLineItem( x_origin_scene + usbl_x_on_vessel * pix_ratio, y_origin_scene - 10 + usbl_z_on_vessel * pix_ratio, x_origin_scene + usbl_x_on_vessel * pix_ratio, y_origin_scene + 10 + usbl_z_on_vessel * pix_ratio) # define labels usbl_label = QGraphicsSimpleTextItem("USBL", usbl_circle) usbl_label.setPos( x_origin_scene - 10 + usbl_x_on_vessel * pix_ratio, y_origin_scene + 10 + usbl_z_on_vessel * pix_ratio) origin_label = QGraphicsSimpleTextItem("VRP", origin) if usbl_x_on_vessel == 0 and usbl_z_on_vessel == 0: origin_label.setPos(x_origin_scene + 10, y_origin_scene - 10) else: origin_label.setPos(x_origin_scene - 10, y_origin_scene + 10) # fit view/scene self.side_scene.setSceneRect( 0, 0, pix_ratio * v_length, pix_ratio * v_height + usbl_z_on_vessel * pix_ratio) self.side_graphicsView.scene().addItem(sea) # add vessel to the scene self.side_graphicsView.scene().addItem(self.item) # add origin to the scene self.side_graphicsView.scene().addItem(origin) self.side_graphicsView.scene().addItem(line_one_origin) self.side_graphicsView.scene().addItem(line_two_origin) if util.find_spec('usblcontroller') is not None: # add usbl self.side_graphicsView.scene().addItem(usbl_circle) self.side_graphicsView.scene().addItem(line_one_usbl) self.side_graphicsView.scene().addItem(line_two_usbl) # add coord system self.side_graphicsView.scene().addItem(line_x_coord) self.side_graphicsView.scene().addItem(line_z_coord) # set background self.side_scene.setBackgroundBrush(Qt.white) # set antialiasing renderhint self.side_graphicsView.setRenderHint(QPainter.Antialiasing)
class TransitionGraphicsItem(QGraphicsObject): # constant values SQUARE_SIDE = 10 ARROW_SIZE = 12 PEN_NORMAL_WIDTH = 1 PEN_FOCUS_WIDTH = 3 posChanged = pyqtSignal('QGraphicsItem') def __init__(self, data): super(QGraphicsObject, self).__init__() self.transitionData = data self.originLine = None self.destinationLine = None self.arrow = None self.textGraphics = None self.middleHandle = None self.graphicsOrigin = self.transitionData.origin.getGraphicsItem() self.graphicsDestination = self.transitionData.destination.getGraphicsItem() # connect position changed event self.graphicsOrigin.posChanged.connect(self.statePosChanged) self.graphicsDestination.posChanged.connect(self.statePosChanged) self.midPointX = (self.graphicsDestination.scenePos().x() + self.graphicsOrigin.scenePos().x()) / 2.0 self.midPointY = (self.graphicsDestination.scenePos().y() + self.graphicsOrigin.scenePos().y()) / 2.0 self.createOriginLine() self.createDestinationLine() self.createArrow() self.createMiddleHandle() self.createIdTextBox() def statePosChanged(self, state): if self.graphicsOrigin == state: self.createOriginLine() elif self.graphicsDestination == state: self.createDestinationLine() self.createArrow() def createOriginLine(self): if self.originLine == None: self.originLine = QGraphicsLineItem(self.midPointX, self.midPointY, self.graphicsOrigin.scenePos().x(), self.graphicsOrigin.scenePos().y(), self) else: self.originLine.setLine(QLineF(self.midPointX, self.midPointY, self.graphicsOrigin.scenePos().x(), self.graphicsOrigin.scenePos().y())) myLine = self.originLine.line() myLine.setLength(myLine.length() - StateGraphicsItem.NODE_WIDTH / 2) self.originLine.setLine(myLine) def createDestinationLine(self): if self.destinationLine == None: self.destinationLine = QGraphicsLineItem(self.midPointX, self.midPointY, self.graphicsDestination.scenePos().x(), self.graphicsDestination.scenePos().y(), self) else: self.destinationLine.setLine(QLineF(self.midPointX, self.midPointY, self.graphicsDestination.scenePos().x(), self.graphicsDestination.scenePos().y())) myLine = self.destinationLine.line() myLine.setLength(myLine.length() - StateGraphicsItem.NODE_WIDTH / 2) self.destinationLine.setLine(myLine) def createArrow(self): # add an arrow to destination line myLine = self.destinationLine.line() myLine.setLength(myLine.length() - TransitionGraphicsItem.ARROW_SIZE) rotatePoint = myLine.p2() - self.destinationLine.line().p2() rightPointX = rotatePoint.x() * math.cos(math.pi / 6) - rotatePoint.y() * math.sin(math.pi / 6) rightPointY = rotatePoint.x() * math.sin(math.pi / 6) + rotatePoint.y() * math.cos(math.pi / 6) rightPoint = QPointF(rightPointX + self.destinationLine.line().x2(), rightPointY + self.destinationLine.line().y2()) leftPointX = rotatePoint.x() * math.cos(-math.pi / 6) - rotatePoint.y() * math.sin(-math.pi / 6) leftPointY = rotatePoint.x() * math.sin(-math.pi / 6) + rotatePoint.y() * math.cos(-math.pi / 6) leftPoint = QPointF(leftPointX + self.destinationLine.line().x2(), leftPointY + self.destinationLine.line().y2()) polygon = QPolygonF() polygon << rightPoint << leftPoint << self.destinationLine.line().p2() << rightPoint if self.arrow == None: self.arrow = QGraphicsPolygonItem(polygon, self) else: self.arrow.setPolygon(polygon) brush = QBrush(Qt.SolidPattern) brush.setColor(Qt.black) self.arrow.setBrush(brush) def createMiddleHandle(self): # create middle handle if self.middleHandle == None: self.middleHandle = RectHandleGraphicsItem(TransitionGraphicsItem.SQUARE_SIDE, self) self.middleHandle.setFlag(QGraphicsItem.ItemIsMovable) self.middleHandle.setPos(self.midPointX, self.midPointY) def createIdTextBox(self): if self.textGraphics == None: self.textGraphics = IdTextBoxGraphicsItem(self.transitionData.name, self) self.textGraphics.textChanged.connect(self.nameChanged) else: self.textGraphics.setPlainText(self.transitionData.name) textWidth = self.textGraphics.boundingRect().width() self.textGraphics.setPos(self.midPointX - textWidth / 2, self.midPointY + TransitionGraphicsItem.SQUARE_SIDE - (TransitionGraphicsItem.SQUARE_SIDE / 2) + 5) def updateMiddlePoints(self, newPosition): self.midPointX = newPosition.x() self.midPointY = newPosition.y() self.createOriginLine() self.createDestinationLine() self.createArrow() self.createIdTextBox() self.posChanged.emit(self) def nameChanged(self, name): self.transitionData.name = name self.createIdTextBox() def boundingRect(self): if self.middleHandle != None: return self.middleHandle.boundingRect() else: return None def disableInteraction(self): if self.middleHandle is not None: self.middleHandle.setFlag(QGraphicsItem.ItemIsMovable, False) self.middleHandle.disableInteraction()
class TransitionGraphicsItem(QGraphicsObject): # constant values SQUARE_SIDE = 10 ARROW_SIZE = 12 PEN_NORMAL_WIDTH = 1 PEN_FOCUS_WIDTH = 3 posChanged = pyqtSignal('QGraphicsItem') def __init__(self, data): super(QGraphicsObject, self).__init__() self.transitionData = data self.originLine = None self.destinationLine = None self.arrow = None self.textGraphics = None self.middleHandle = None self.graphicsOrigin = self.transitionData.origin.getGraphicsItem() self.graphicsDestination = self.transitionData.destination.getGraphicsItem( ) # connect position changed event self.graphicsOrigin.posChanged.connect(self.statePosChanged) self.graphicsDestination.posChanged.connect(self.statePosChanged) self.midPointX = (self.graphicsDestination.scenePos().x() + self.graphicsOrigin.scenePos().x()) / 2.0 self.midPointY = (self.graphicsDestination.scenePos().y() + self.graphicsOrigin.scenePos().y()) / 2.0 self.createOriginLine() self.createDestinationLine() self.createArrow() self.createMiddleHandle() self.createIdTextBox() def statePosChanged(self, state): if self.graphicsOrigin == state: self.createOriginLine() elif self.graphicsDestination == state: self.createDestinationLine() self.createArrow() def createOriginLine(self): if self.originLine == None: self.originLine = QGraphicsLineItem( self.midPointX, self.midPointY, self.graphicsOrigin.scenePos().x(), self.graphicsOrigin.scenePos().y(), self) else: self.originLine.setLine( QLineF(self.midPointX, self.midPointY, self.graphicsOrigin.scenePos().x(), self.graphicsOrigin.scenePos().y())) myLine = self.originLine.line() myLine.setLength(myLine.length() - StateGraphicsItem.NODE_WIDTH / 2) self.originLine.setLine(myLine) def createDestinationLine(self): if self.destinationLine == None: self.destinationLine = QGraphicsLineItem( self.midPointX, self.midPointY, self.graphicsDestination.scenePos().x(), self.graphicsDestination.scenePos().y(), self) else: self.destinationLine.setLine( QLineF(self.midPointX, self.midPointY, self.graphicsDestination.scenePos().x(), self.graphicsDestination.scenePos().y())) myLine = self.destinationLine.line() myLine.setLength(myLine.length() - StateGraphicsItem.NODE_WIDTH / 2) self.destinationLine.setLine(myLine) def createArrow(self): # add an arrow to destination line myLine = self.destinationLine.line() myLine.setLength(myLine.length() - TransitionGraphicsItem.ARROW_SIZE) rotatePoint = myLine.p2() - self.destinationLine.line().p2() rightPointX = rotatePoint.x() * math.cos( math.pi / 6) - rotatePoint.y() * math.sin(math.pi / 6) rightPointY = rotatePoint.x() * math.sin( math.pi / 6) + rotatePoint.y() * math.cos(math.pi / 6) rightPoint = QPointF(rightPointX + self.destinationLine.line().x2(), rightPointY + self.destinationLine.line().y2()) leftPointX = rotatePoint.x() * math.cos( -math.pi / 6) - rotatePoint.y() * math.sin(-math.pi / 6) leftPointY = rotatePoint.x() * math.sin( -math.pi / 6) + rotatePoint.y() * math.cos(-math.pi / 6) leftPoint = QPointF(leftPointX + self.destinationLine.line().x2(), leftPointY + self.destinationLine.line().y2()) polygon = QPolygonF() polygon << rightPoint << leftPoint << self.destinationLine.line().p2( ) << rightPoint if self.arrow == None: self.arrow = QGraphicsPolygonItem(polygon, self) else: self.arrow.setPolygon(polygon) brush = QBrush(Qt.SolidPattern) brush.setColor(Qt.black) self.arrow.setBrush(brush) def createMiddleHandle(self): # create middle handle if self.middleHandle == None: self.middleHandle = RectHandleGraphicsItem( TransitionGraphicsItem.SQUARE_SIDE, self) self.middleHandle.setFlag(QGraphicsItem.ItemIsMovable) self.middleHandle.setPos(self.midPointX, self.midPointY) def createIdTextBox(self): if self.textGraphics == None: self.textGraphics = IdTextBoxGraphicsItem(self.transitionData.name, self) self.textGraphics.textChanged.connect(self.nameChanged) else: self.textGraphics.setPlainText(self.transitionData.name) textWidth = self.textGraphics.boundingRect().width() self.textGraphics.setPos( self.midPointX - textWidth / 2, self.midPointY + TransitionGraphicsItem.SQUARE_SIDE - (TransitionGraphicsItem.SQUARE_SIDE / 2) + 5) def updateMiddlePoints(self, newPosition): self.midPointX = newPosition.x() self.midPointY = newPosition.y() self.createOriginLine() self.createDestinationLine() self.createArrow() self.createIdTextBox() self.posChanged.emit(self) def nameChanged(self, name): self.transitionData.name = name self.createIdTextBox() def boundingRect(self): if self.middleHandle != None: return self.middleHandle.boundingRect() else: return None def disableInteraction(self): if self.middleHandle is not None: self.middleHandle.setFlag(QGraphicsItem.ItemIsMovable, False) self.middleHandle.disableInteraction()
class MagnetButtonItem(GraphicsWidget): fill_brush = QBrush(QColor(255, 255, 255)) def __init__(self, magnet, size, direction=1.0, parent=None): super(MagnetButtonItem, self).__init__(parent) self.magnet = magnet self.direction = direction tri_poly = QPolygonF([ QPointF(-size, direction * size / 2.0), QPointF(0.0, -direction * size / 2.0), QPointF(size, direction * size / 2.0) ]) self.triangle = QGraphicsPolygonItem(tri_poly, parent=self) self.triangle.setBrush(self.fill_brush) self.setFixedHeight(size) self.setFixedWidth(size) self._bounds = QRectF(0, 0, 1, 1) self._boundingRect = None self.anchor = Point(0.5, 0.5) self._lastScene = None self._lastTransform = None self.setToolTip(self.magnet.name) self.default_opacity = 0.7 self.disabled_opacity = 0.4 self.hovering_opacity = 1.0 self.setOpacity(self.default_opacity) self.enabled = True def mouseClickEvent(self, ev): if not self.enabled: return if self.direction == 1.0: self.magnet.increase_kick() elif self.direction == -1.0: self.magnet.decrease_kick() ev.accept() def hoverEvent(self, ev): #Note this is the custom pyqtgraph.GraphicsWidget hover event, not the Qt version. if not self.enabled: return if ev.enter: self.setOpacity(self.hovering_opacity) elif ev.exit: self.setOpacity(self.default_opacity) def disable(self): self.enabled = False self.setOpacity(self.disabled_opacity) def enable(self): self.enabled = True self.setOpacity(self.default_opacity) def boundingRect(self): return self.triangle.mapToParent( self.triangle.boundingRect()).boundingRect() def viewTransformChanged(self): # called whenever view transform has changed. # Do this here to avoid double-updates when view changes. self.updateTransform() def dataBounds(self, axis, frac=1.0, orthoRange=None): # """Called by ViewBox for determining the auto-range bounds. return None def updateTransform(self): # update transform such that this item has the correct orientation # and scaling relative to the scene, but inherits its position from its # parent. # This is similar to setting ItemIgnoresTransformations = True, but # does not break mouse interaction and collision detection. p = self.parentItem() if p is None: pt = QTransform() else: pt = p.sceneTransform() if pt == self._lastTransform: return t = pt.inverted()[0] # reset translation t.setMatrix(t.m11(), t.m12(), t.m13(), t.m21(), t.m22(), t.m23(), 0, 0, t.m33()) self.setTransform(t) self._lastTransform = pt def setNewBounds(self): """Update the item's bounding rect to match the viewport""" self._boundingRect = None ## invalidate bounding rect, regenerate later if needed. self.prepareGeometryChange() def itemChange(self, change, value): if change == QGraphicsItem.ItemSceneChange: s = value ls = self.scene() if ls is not None: ls.sigPrepareForPaint.disconnect(self.updateTransform) if s is not None: try: s.sigPrepareForPaint.connect(self.updateTransform) except AttributeError: #When the whole GUI closes, all the magnet buttons get re-parented to a plain old QGraphicsScene, which doesnt have the signal. pass self.updateTransform() return super(MagnetButtonItem, self).itemChange(change, value)
class GraphicLine(QGraphicsLineItem): """ This class is a graphic line with an arrow which connects two blocks in the scene. Attributes ---------- origin : QGraphicsRectItem Origin rect of the line. destination : QGraphicsRectItem Destination rect of the line. scene : QGraphicsScene Current drawing scene. brush : QBrush Brush to draw the arrow. pen : QPen Pen to draw the arrow. arrow_head : QGraphicsPolygonItem Final arrow of the line. arrow_size : int Size of the head of the arrow. dim_label : QGraphicsTextItem Text showing the dimensions of the edge. is_valid : bool Flag monitoring whether the connection is consistent. Methods ---------- gen_endpoints(QRectF, QRectF) Returns the shortest connection between the two rects. draw_arrow() Draws the polygon for the arrow. set_valid(bool) Assign validity for this line. update_dims(tuple) Update the line dimensions. update_pos(QRectF) Update the line position given the new rect position. remove_self() Delete this line. """ def __init__(self, origin: QGraphicsRectItem, destination: QGraphicsRectItem, scene): super(GraphicLine, self).__init__() self.origin = origin self.destination = destination self.scene = scene # This flag confirms a legal connection self.is_valid = True # Get the four sides of the rects destination_lines = u.get_sides_of( self.destination.sceneBoundingRect()) origin_lines = u.get_sides_of(self.origin.sceneBoundingRect()) # Get the shortest edge between the two blocks self.setLine(self.gen_endpoints(origin_lines, destination_lines)) self.brush = QBrush(QColor(style.GREY_0)) self.pen = QPen(QColor(style.GREY_0)) self.pen.setWidth(4) self.pen.setCapStyle(Qt.RoundCap) self.pen.setJoinStyle(Qt.RoundJoin) self.setPen(self.pen) # Dimensions labels self.dim_label = QGraphicsTextItem() self.dim_label.setZValue(6) self.scene.addItem(self.dim_label) # Arrow head self.arrow_head = QGraphicsPolygonItem() self.arrow_head.setPen(self.pen) self.arrow_head.setBrush(self.brush) self.arrow_size = 15.0 self.draw_arrow() @staticmethod def gen_endpoints(origin_sides: dict, destination_sides: dict) -> QLineF: """ This method finds the shortest path between two rectangles. Parameters ---------- origin_sides : dict The dictionary {side_label: side_size} of the starting rect. destination_sides : dict The dictionary {side_label: side_size} of the ending rect. Returns ---------- QLineF The shortest line. """ # Init the line with the maximum possible value shortest_line = QLineF(-sys.maxsize / 2, -sys.maxsize / 2, sys.maxsize / 2, sys.maxsize / 2) for o_side, origin_side in origin_sides.items(): o_mid_x, o_mid_y = u.get_midpoint(o_side, origin_side) for d_side, destination_side in destination_sides.items(): d_mid_x, d_mid_y = u.get_midpoint(d_side, destination_side) # Update line line = QLineF(o_mid_x, o_mid_y, d_mid_x, d_mid_y) if line.length() < shortest_line.length(): shortest_line = line return shortest_line def draw_arrow(self) -> None: """ This method draws an arrow at the end of the line. """ polygon_arrow_head = QPolygonF() # Compute the arrow angle angle = math.acos(self.line().dx() / self.line().length()) angle = ((math.pi * 2) - angle) # Compute the direction where the arrow points (1 up, -1 down) arrow_direction = 1 if math.asin(self.line().dy() / self.line().length()) < 0: arrow_direction = -1 # First point of the arrow tail arrow_p1 = self.line().p2() - arrow_direction * QPointF( arrow_direction * math.sin(angle + math.pi / 2.5) * self.arrow_size, math.cos(angle + math.pi / 2.5) * self.arrow_size) # Second point of the arrow tail arrow_p2 = self.line().p2() - arrow_direction * QPointF( arrow_direction * math.sin(angle + math.pi - math.pi / 2.5) * self.arrow_size, math.cos(angle + math.pi - math.pi / 2.5) * self.arrow_size) # Third point is the line end polygon_arrow_head.append(self.line().p2()) polygon_arrow_head.append(arrow_p2) polygon_arrow_head.append(arrow_p1) # Add the arrow to the scene self.arrow_head.setZValue(1) self.arrow_head.setParentItem(self) self.arrow_head.setPolygon(polygon_arrow_head) def set_valid(self, valid: bool) -> None: """ This method changes the arrow style: if the connection is not valid the arrow becomes red, otherwise it remains grey with dimensions displayed. Parameters ---------- valid : bool New value for the legality flag. """ if valid: self.is_valid = True self.pen.setColor(QColor(style.GREY_0)) self.brush.setColor(QColor(style.GREY_0)) self.dim_label.setVisible(False) else: self.is_valid = False self.pen.setColor(QColor(style.RED_2)) self.brush.setColor(QColor(style.RED_2)) if self.scene.is_dim_visible: self.dim_label.setVisible(True) def update_dims(self, dims: tuple) -> None: """ This method updates the input & output dimensions. Parameters ---------- dims : tuple The new dimensions to update. """ self.dim_label.setHtml("<div style = 'background-color: " + style.RED_2 + "; color: white; font-family: consolas;'>" + str(dims) + "</div>") self.dim_label.setPos(self.line().center()) def update_pos(self, new_target: QRectF): """ This method updates the line as it origin or its destination has changed location. Parameters ---------- new_target : QRectF """ if new_target == self.destination: self.destination = new_target elif new_target == self.origin: self.origin = new_target # Get the four sides of the rects destination_lines = u.get_sides_of( self.destination.sceneBoundingRect()) origin_lines = u.get_sides_of(self.origin.sceneBoundingRect()) # Get the shortest edge between the two blocks self.setLine(self.gen_endpoints(origin_lines, destination_lines)) self.draw_arrow() self.dim_label.setPos(self.line().center()) def remove_self(self) -> None: """ The line is removed from the scene along with origin and destination pointers. """ self.scene.removeItem(self) self.scene.edges.remove(self) self.scene.removeItem(self.dim_label) self.origin = None self.destination = None
def on_qAction15_triggered(self): item = QGraphicsPolygonItem() points = [QPointF(0, -40), QPointF(60, 40), QPointF(-60, 40)] item.setPolygon(QPolygonF(points)) item.setBrush(QBrush(Qt.magenta)) self.__setItemProperties(item, "三角形")
def on_actItem_Triangle_triggered(self): item=QGraphicsPolygonItem() points=[QPointF(0,-40), QPointF(60,40), QPointF(-60,40)] item.setPolygon(QPolygonF(points)) item.setBrush(QBrush(Qt.magenta)) #设置填充颜色 self.__setItemProperties(item,"三角形")
def create_cross(): item = QGraphicsPolygonItem(qt_drawings.cross_polygon) item.setBrush(qt_drawings.red_brush) item.setPen(qt_drawings.red_pen) return item