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 set_range(self, SCALE_FACTOR): '''It gives the object a QGraphicsPolygonItem to attack at a certain range ''' # create points vector self.range = SCALE_FACTOR points = [ QPointF(1, 0), QPointF(2, 0), QPointF(3, 1), QPointF(3, 2), QPointF(2, 3), QPointF(1, 3), QPointF(0, 2), QPointF(0, 1) ] # scale points points = [p * SCALE_FACTOR for p in points] # create polygon self.polygon = QPolygonF(points) # create QGraphicsPolygonItem self.attack_area = QGraphicsPolygonItem(self.polygon, self) self.attack_area.setPen(QPen(Qt.DotLine)) # move the polygon poly_center = QPointF(1.5 * SCALE_FACTOR, 1.5 * SCALE_FACTOR) poly_center = self.mapToScene(poly_center) minion_center = QPointF(self.x() + self.pixmap().width() / 2, self.y() + self.pixmap().height() / 2) ln = QLineF(poly_center, minion_center) self.attack_area.setPos(self.x() + ln.dx(), self.y() + ln.dy())
def mousePressEvent(self, e) : #logger.debug('DragPoly.mousePressEvent, at point: %s on scene: %s '%\ # (str(e.pos()), str(e.scenePos()))) # self.__class__.__name__ QGraphicsPolygonItem.mousePressEvent(self, e) # points would not show up w/o this line #print("DragPoly is selected: ", self.isSelected()) #print('XXX DragPoly.mousePressEvent button L/R/M = 1/2/4: ', e.button()) #print('XXX DragPoly.mousePressEvent Left: ', e.button()==Qt.LeftButton) if e.button()==Qt.RightButton : self._end_of_add = True ps = e.scenePos() #print('%s.mousePressEvent itemAt:' % self.__class__.__name__, self.scene().itemAt(ps)) t = self.scene().views()[0].transform() item_sel = self.scene().itemAt(ps.x(), ps.y(), t) #item_sel = self.scene().itemAt(ps) if self.lst_ctl_points is None : logger.warning('DragPoly.lst_ctl_points is None') return if item_sel in self.lst_ctl_points : self.indx_sel = self.lst_ctl_points.index(item_sel) print('XXX DragPoly.mousePressEvent index_selected = ', self.indx_sel) self.set_drag_mode(EDIT) self.set_child_item_sel(item_sel) if item_sel == self.ped : self.control_point_menu() if self.poly0 is not None : del self.poly0 self.poly0 = QPolygonF(self.polygon()) self.pos0 = [gi.pos() for gi in self.lst_ctl_points]
def mouseMoveEvent(self, e) : QGraphicsPolygonItem.mouseMoveEvent(self, e) #logger.debug('%s.mouseMoveEvent' % self.__class__.__name__) #print('%s.mouseMoveEvent, at point: ' % self.__class__.__name__, e.pos(), ' scenePos: ', e.scenePos()) #print('XXX mouseMoveEvent scenePos(), e.lastScenePos:', e.scenePos(), e.lastScenePos()) dp = e.scenePos() - e.lastScenePos() if self._drag_mode == MOVE and self.isSelected() : self.moveBy(dp.x(), dp.y()) elif self._drag_mode == ADD : if self._end_of_add : return #print('%s.mouseMoveEvent _drag_mode=ADD' % self.__class__.__name__) poly = self.polygon() point = e.scenePos() if poly.size()==1 : poly.append(point) else : poly.replace(poly.size()-1, point) self.setPolygon(poly) elif self._drag_mode == EDIT : o = self.polygon() i = self.child_item_sel() o.replace(self.indx_sel, e.scenePos() - self.pos()) #!!! # self.pos() in parent??? self.setPolygon(o) self.move_control_points()
def mouseReleaseEvent(self, e): #logger.debug('DragPoly.mouseReleaseEvent') # % self.__class__.__name__) QGraphicsPolygonItem.mouseReleaseEvent(self, e) if self._drag_mode == ADD : poly = self.polygon() point = e.scenePos() ind_last = poly.count()-1 #print('XXX polygone ind_last = %d' % ind_last) if self._end_of_add : poly.replace(ind_last, point) self.ungrabMouse() self.set_drag_mode() else : poly.append(point) self.setPolygon(poly) if self._end_of_add : self.set_control_points() #self.setSelected(False) if self._drag_mode == EDIT : self.set_child_item_sel(None) self.set_drag_mode()
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()
def __init__(self): super().__init__() # initialize attack range (area) self.attack_area = QGraphicsPolygonItem() self.attack_dest = QPointF(0, 0) self.has_target = False # set the graphics self.setPixmap( QPixmap('./res/imgs/lol_tower.png').scaled(80, 80, Qt.KeepAspectRatio)) # initializes health h = Bar(self) h.set_max_val(250) h.set_current_val(250) self.set_health(h) self.attack = 30 # create points vector points = [ QPointF(1, 0), QPointF(2, 0), QPointF(3, 1), QPointF(3, 2), QPointF(2, 3), QPointF(1, 3), QPointF(0, 2), QPointF(0, 1) ] # scale points SCALE_FACTOR = 100 points = [p * SCALE_FACTOR for p in points] self.range = SCALE_FACTOR # create polygon self.polygon = QPolygonF(points) # create QGraphicsPolygonItem self.attack_area = QGraphicsPolygonItem(self.polygon, self) self.attack_area.setPen(QPen(Qt.DotLine)) # move the polygon poly_center = QPointF(1.5 * SCALE_FACTOR, 1.5 * SCALE_FACTOR) poly_center = self.mapToScene(poly_center) tower_center = QPointF(self.x() + 40, self.y() + 40) ln = QLineF(poly_center, tower_center) self.attack_area.setPos(self.x() + ln.dx(), self.y() + ln.dy()) # connect a timer to acquire target self.damage_timer = QTimer() self.damage_timer.timeout.connect(self.acquire_target) self.damage_timer.start(1000) # allow responding to hover events self.setAcceptHoverEvents(True)
def __init__(self, center, radius, parent=None): QGraphicsPolygonItem.__init__(self, makeHexagon(center, radius), parent) self._center = center self._radius = radius self.setZValue(0) self.setBoundingRegionGranularity(1.0) self.setBrush(QBrush(QColor(0, center.y() % 256, center.x() % 256))) self.setPen(QPen(Qt.NoPen)) self.setAcceptHoverEvents(True)
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__() 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 __init__(self, obj, parent=None, scene=None,\ brush=QBrush(), pen=QPen(Qt.blue, 0, Qt.SolidLine)) : """Adds QGraphics(Polygon)Item to the scene. Parameters obj : QPointF or shape type e.g. QPolygonF obj is QPointF - shape parameters are defined at first mouse click obj is QPolygonF - it will be drawn as is """ logger.debug('In DragPoly') poly = None if isinstance(obj, QPolygonF) : poly = obj elif isinstance(obj, QPointF) : poly = QPolygonF() poly.append(obj) #print('XXX DragPoly 0-point QPolygonF() size = %d' % poly.size()) if poly is None : logger.warning('DragPoly - wrong init object type:', str(obj)) return self._dragtype = POLY self._end_of_add = False self.poly0 = None parent_for_base = None QGraphicsPolygonItem.__init__(self, poly, parent_for_base) #DragBase.__init__(self, parent, brush, pen) # is called inside QGraphicsPolygonItem logger.debug('In DragPoly - superclass initialization is done') if isinstance(obj, QPointF) : self._drag_mode = ADD logger.debug('set elf._drag_mode = ADD, ADD:%d _drag_mode:%d' % (ADD, self._drag_mode)) if scene is not None: scene.addItem(self) if self._drag_mode == ADD : self.grabMouse() # makes available mouseMoveEvent logger.debug('In DragPoly mode grabMouse()') self.setAcceptHoverEvents(True) #self.setAcceptTouchEvents(True) #self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton) self.setPen(self._pen_pos) self.setBrush(self._brush) # Flags: ItemIsPanel, ItemClipsChildrenToShape, ItemIsSelectable, # ItemIsMovable, itemClipsToShape, ItemSendsScenePositionChanges self.setFlags(self.ItemIsSelectable)
def triangulation(self): if self.chkTriangles.isChecked() == True: self.tri1 = [] self.tri2 = [] self.leftSimplices = Delaunay(self.leftPoints).simplices if self.initialPoints == True and self.addPoints == True: Pen = QPen(QtCore.Qt.cyan) print(1) elif self.addPoints == True: Pen = QPen(QtCore.Qt.blue) print(2) else: Pen = QPen(QtCore.Qt.red) for triangle in self.leftSimplices.tolist(): #TriLeft = self.leftPoints[triangle] #TriRight = self.rightPoints[triangle] #leftTriangles.append(Tri) # print(self.leftPoints[triangle]) #print(self.leftPoints[triangle[0]]) pointA = QtCore.QPointF(self.leftPoints[triangle[0]][0], self.leftPoints[triangle[0]][1]) PointB = QtCore.QPointF(self.leftPoints[triangle[1]][0], self.leftPoints[triangle[1]][1]) PointC = QtCore.QPointF(self.leftPoints[triangle[2]][0], self.leftPoints[triangle[2]][1]) self.drawTriangle = QtGui.QPolygonF([pointA, PointB, PointC]) self.tri1Item = QGraphicsPolygonItem(self.drawTriangle) self.tri1Item.setPen(Pen) self.startSetImg.addItem(self.tri1Item) self.tri1.append(self.tri1Item) pointAA = QtCore.QPointF(self.rightPoints[triangle[0]][0], self.rightPoints[triangle[0]][1]) PointBB = QtCore.QPointF(self.rightPoints[triangle[1]][0], self.rightPoints[triangle[1]][1]) PointCC = QtCore.QPointF(self.rightPoints[triangle[2]][0], self.rightPoints[triangle[2]][1]) self.drawTriangle1 = QtGui.QPolygonF( [pointAA, PointBB, PointCC]) self.tri2Item = QGraphicsPolygonItem(self.drawTriangle1) self.tri2Item.setPen(Pen) self.endSetImg.addItem(self.tri2Item) self.tri2.append(self.tri2Item) else: #print("111111111") for item1 in self.tri1: self.startSetImg.removeItem(item1) for item2 in self.tri2: self.endSetImg.removeItem(item2)
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)
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 __init__(self, parent=None): super(ASCGraphicsView, self).__init__(parent) self.scene = QGraphicsScene(self) self.raw_img_item = QGraphicsPixmapItem() self.raw_img_item.setZValue(0) self.anno_img_item = QGraphicsPixmapItem() self.anno_img_item.setZValue(1) self.cross_bar_v_line_item = QGraphicsLineItem() self.cross_bar_h_line_item = QGraphicsLineItem() self.cross_bar_v_line_item.setZValue(100) self.cross_bar_h_line_item.setZValue(100) self.cross_bar_v_line_item.setPen( QPen(Qt.blue, 0, Qt.DotLine, Qt.FlatCap, Qt.RoundJoin)) self.cross_bar_h_line_item.setPen( QPen(Qt.blue, 0, Qt.DotLine, Qt.FlatCap, Qt.RoundJoin)) self.paint_brush_circle_item = QGraphicsEllipseItem() self.paint_brush_rect_item = QGraphicsPolygonItem() self.paint_brush_circle_item.setZValue(10) self.paint_brush_rect_item.setZValue(11) self.paint_brush_circle_item.setVisible(False) self.paint_brush_rect_item.setVisible(False) self.paint_brush_circle_item.setPen( QPen(Qt.red, 0, Qt.DotLine, Qt.FlatCap, Qt.RoundJoin)) self.paint_brush_rect_item.setPen( QPen(Qt.red, 0, Qt.DotLine, Qt.FlatCap, Qt.RoundJoin)) self.scene.addItem(self.raw_img_item) self.scene.addItem(self.anno_img_item) self.scene.addItem(self.cross_bar_v_line_item) self.scene.addItem(self.cross_bar_h_line_item) self.scene.addItem(self.paint_brush_circle_item) self.scene.addItem(self.paint_brush_rect_item) self.setScene(self.scene) self.setViewport(QOpenGLWidget()) self._last_button_press = Qt.NoButton self._last_pos_middle_button = None self._last_pos_right_button = None self._brush_stats = {'type': BRUSH_TYPE_NO_BRUSH, 'size': 5} self.setResizeAnchor(QGraphicsView.AnchorViewCenter) self.slice_scroll_bar = None self.image_size = None self.is_valid = False
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 itemChange(self, change, value) : #print('%s.itemChange' % (self.__class__.__name__), ' change: %d, value:' % change, value) valnew = QGraphicsPolygonItem.itemChange(self, change, value) if change == self.ItemSelectedHasChanged : #self.set_control_points_visible(visible=True) self.set_control_points_visible(visible=self.isSelected()) return valnew
def draw_convex_hull(self): if len(self.annotation_manager.annotations_rect[ self.scene.image_name]) > 1: if self.scene.polygon is not None: self.scene.removeItem(self.scene.polygon) self.scene.polygon = None points = [] for annot in self.annotation_manager.annotations_rect[ self.scene.image_name]: x, y, w, h = annot x = int(x) y = int(y) w = int(w) h = int(h) points.append((x, y)) points.append((x + w, y)) points.append((x, y + h)) points.append((x + w, y + h)) brush = QBrush(QColor("#1E90FF")) pen = QPen(brush, 3) polygon = QPolygonF([ QPointF(x[0, 0], x[0, 1]) for x in convexHull(np.array(points)) ]) self.scene.polygon = QGraphicsPolygonItem(polygon) self.scene.polygon.setPen(pen) self.scene.addItem(self.scene.polygon) else: if self.scene.polygon is not None: self.scene.removeItem(self.scene.polygon) self.scene.polygon = None
def draw(self,qwidget_obj,qp,GISView_view): qPolygonFsToScreen = GISView_view.toScreenPolygon(self.List_allvertex) qwidget_obj.scene.addItem(QGraphicsPolygonItem(QPolygonF(qPolygonFsToScreen))) #pen = QPen(Qt.blue, 1, Qt.SolidLine) #qwidget_obj.scene.addLine(qLineF , pen) return
def __init__(self): super().__init__() # set speed self.speed = 0 self.attack = 1 # set pos / destination self.x_prev = 0 self.y_prev = 0 self.setPos(0, 0) self.destination = QPointF(0, 0) # initialize attack range (area) self.attack_area = QGraphicsPolygonItem() self.attack_dest = QPointF(0, 0) self.has_target = False
def __init__(self, qPointList, bot, rType): # QGraphicsItemGroup.__init__(self) self.rType = rType #射线类型雷达 if rType == "poly": self.item = QGraphicsPolygonItem() #提供一个多边形item self.polygon = QPolygonF(qPointList) self.item.setPolygon(self.polygon) self.robot = bot #范围类型雷达 elif rType == "round": self.item = QGraphicsEllipseItem() #提供一个椭圆item self.item.setRect(qPointList[0], qPointList[1], qPointList[2], qPointList[3]) self.robot = bot color = QColor(255, 100, 6, 10) #设置雷达的颜色, brush = QBrush(color) pen = QPen(color) self.item.setBrush(brush) self.item.setPen(pen) self.addToGroup(self.item)
def polyClose(self): #make into hot key not button if self.measuring_area: if self.line_count > 2: #cant make polygon w/ two lines self.measuring_area = False A = self.A.calcArea() self.areaValues = np.append(self.areaValues, A) #add area values #draw permanent polygon points = [ QtCore.QPointF(x, y) for x, y in zip(self.A.x, self.A.y) ] self.scene.polyItem2 = QGraphicsPolygonItem( QtGui.QPolygonF(points)) self.scene.polyItem2.setBrush( QtGui.QBrush(QtGui.QColor(255, 255, 255, 127))) if self.scene.polyItem: self.scene.removeItem( self.scene.polyItem) #remove mouseover polygon self.scene.polyItem = False #remove mouseover polygon self.scene.removeItem(self.scene.testline) self.scene.testline = False self.scene.addItem(self.scene.polyItem2) #shade in polygon self.parent().statusbar.showMessage( 'Polygon area measurement completed') self.parent().areaButton.setChecked(False) self.parent().bezier.setEnabled( True) #make bezier fit available again else: print("cannot draw polygon with fewer than three vertices")
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 __init__(self, points, filled=False): super().__init__() polygon = QPolygonF() for point in points: polygon.append(QPoint(point[0], point[1])) p = QGraphicsPolygonItem(polygon) self.addToGroup(p)
def draw_roi_polygon(self): if len(self.annotation_manager.roi_points[self.image_name]) > 2: if self.roi_polygon != None: self.removeItem(self.roi_polygon) self.roi_polygon = None brush = QBrush(QColor("#fc8803")) pen = QPen(brush, 5) polygon = QPolygonF([ QPointF(x[0], x[1]) for x in np.array( self.annotation_manager.roi_points[self.image_name]) ]) self.roi_polygon = QGraphicsPolygonItem(polygon) self.roi_polygon.setPen(pen) self.addItem(self.roi_polygon) else: if self.roi_polygon != None: self.removeItem(self.roi_polygon) self.roi_polygon = None
def __init__(self, parent=None): super(Tower, self).__init__(parent) self.setPixmap(QPixmap(':/Resources/images/Tower.png')) self.setScale(0.5) self.points = [ QPointF(1, 0), QPointF(2, 0), QPointF(3, 1), QPointF(3, 2), QPointF(2, 3), QPointF(1, 3), QPointF(0, 2), QPointF(0, 1) ] for point in self.points: point.setX(point.x() * Tower.SCALE_FACTOR) point.setY(point.y() * Tower.SCALE_FACTOR) self.polygon = QPolygonF(self.points) self.border = QGraphicsPolygonItem(self.polygon, self) # self.border.setPen(QPen(Qt.red)) self.border.setScale(0.5) self.border.setPen(QPen(Qt.DashLine)) self.poly_center = QPointF(1.5, 1.5) self.poly_center *= Tower.SCALE_FACTOR self.poly_center = self.mapToScene(self.poly_center) self.tower_center = QPointF(self.x() + 50, self.y() + 50) self.line = QLineF(self.poly_center, self.tower_center) self.border.setPos(self.border.x() + self.line.dx(), self.border.y() + self.line.dy()) # self.attack_destination = QPointF(800,0) self.timer = QTimer() self.timer.timeout.connect(lambda: self.accquire_target()) self.timer.start(1000)
def __init__(self, parent=None): super().__init__() # bool to check if it is available self.available = False # set store gui self.gui = Store() # set graphics self.setPixmap(QPixmap('./res/imgs/blue_chest.png').scaled(80, 80, Qt.KeepAspectRatio)) # create points vector points = [QPointF(1, 0), QPointF(2, 0), QPointF(3, 1), QPointF(3, 2), QPointF(2, 3), QPointF(1, 3), QPointF(0, 2), QPointF(0, 1)] # scale points SCALE_FACTOR = 100 points = [p * SCALE_FACTOR for p in points] # create polygon self.polygon = QPolygonF(points) # create QGraphicsPolygonItem self.available_area = QGraphicsPolygonItem(self.polygon, self) self.available_area.setPen(QPen(Qt.DotLine)) # move the polygon poly_center = QPointF(1.5 * SCALE_FACTOR, 1.5 * SCALE_FACTOR) poly_center = self.mapToScene(poly_center) store_center = QPointF(self.x() + 40, self.y() + 40) ln = QLineF(poly_center, store_center) self.available_area.setPos(self.x() + ln.dx(), self.y() + ln.dy()) # connect the timer to acquire_champion self.timer = QTimer() self.timer.timeout.connect(self.acquire_champion) self.timer.start(1000)
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 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 mousePressEvent(self, event, image_item): pos = event.scenePos() if self._item is None: item = QGraphicsPolygonItem(QPolygonF([pos])) self._item = item self._item.setPen(self.pen()) self._scene.addItem(item) self._scene.setMessage("Press Enter to finish the polygon.") polygon = self._item.polygon() polygon.append(pos) self._item.setPolygon(polygon) event.accept()
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 on_mouseDoubleClick(self, point): # 鼠标双击事件,调用相应的对话框,设置填充颜色、线条颜色或字体 # QMessageBox.warning(self, "debug","on_mouseDoubleClick!") pointScene = self.view.mapToScene(point) # 转换到Scene坐标 # QGraphicsItem *item=NULL item = self.scene.itemAt(pointScene, self.view.transform()) # 获取光标下的绘图项 item_type = item.type() # QMessageBox.warning(self, "debug",str(item_type)+'<==>'+str(QGraphicsLineItem.Type)) if item == None or item_type == None: # 没有绘图项 QMessageBox.warning(self, "debug", "No item found!") return # switch (item_type): #绘图项的类型 if item_type == 3: # QGraphicsRectItem.Type: #矩形框 # 强制类型转换 theItem = QGraphicsRectItem(item) self.setBrushColor(theItem) return elif item_type == 4: # QGraphicsEllipseItem.Type: #椭圆和圆都是 QGraphicsEllipseItem theItem = QGraphicsEllipseItem(item) self.setBrushColor(theItem) return elif item_type == 5: # QGraphicsPolygonItem.Type: #梯形和三角形 theItem = QGraphicsPolygonItem(item) self.setBrushColor(theItem) return elif item_type == 6: # QGraphicsLineItem.Type: #直线,设置线条颜色 theItem = QGraphicsLineItem(item) pen = theItem.pen() color = theItem.pen().color() color = QColorDialog.getColor(color, self, "选择线条颜色") if color.isValid(): pen.setColor(color) theItem.setPen(pen) return elif item_type == 8: # QGraphicsTextItem.Type: #文字,设置字体 theItem = QGraphicsTextItem(item) font = theItem.font() ok = False font, ok = QFontDialog.getFont(self) if ok: theItem.setFont(font) return
def cloneBody(self, bodyspecName, dropPos, itemId=None, width=0): bodyDef = self.bodies[bodyspecName]; if not itemId: if bodyspecName not in self.nameIndex: self.nameIndex[bodyspecName] = 0; self.nameIndex[bodyspecName] += 1; itemId = "{}{}".format(bodyspecName, self.nameIndex[bodyspecName]); body = BodyItem(itemId, bodyspecName, 2); self.bodyInstances.append(body); body.setPos(dropPos); group = QGraphicsItemGroup(body); self.renderScene.addItem(body); width = width*self.UNITS_PER_METER or self.DEFAULT_BODY_SIZE; for shape in bodyDef["shapes"]: vertices = shape["vertices"]; if shape["type"] == "POLYGON": newItem = QGraphicsPolygonItem(QPolygonF(vertices)); if shape["type"] == "CIRCLE": p1, p2 = vertices radius = math.hypot(p2.x()-p1.x(), p2.y()-p1.y()); newItem = QGraphicsEllipseItem(p1.x()-radius, p1.y()-radius, radius*2, radius*2); pen = QPen(); pen.setWidth(0); newItem.setPen(pen); newItem.setParentItem(group); bounding = group.childrenBoundingRect(); imagePath = None; height = 0; if (bodyDef["image"]): imagePath = bodyDef["image"]; pixmap = QPixmap(imagePath); body.setPixmap(pixmap); pm = QGraphicsPixmapItem(pixmap.scaledToWidth(width), body); body.setImg(pm); pm.setFlags(QGraphicsItem.ItemStacksBehindParent); pm.setOffset(0, -pm.boundingRect().height()); group.setScale(width/self.TRANSCOORD_X); height = pm.boundingRect().height(); else: group.setScale(width/bounding.width()); height = bounding.height(); for item in body.childItems(): item.setPos(item.pos().x(), item.pos().y() + height) body.updateBorder(); return body;
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()