class AnimationSpinner(QLabel): def __init__(self, parent=None): QLabel.__init__(self, parent) brightness = parent.palette().color(QPalette.Window).valueF() self._bw = brightness < 0.5 and 1 or 0 self._steps = 12 self._setup() self._isRunning = False self.animationTimer = None def _setup(self): steps = self._steps anglestep = 360. / steps fillstep = 0.6 / (steps - 1) self._fillsteps = [0.71 - i * fillstep for i in range(steps)] self._coords = [coordinates(8, 8, 6, anglestep*i) for i in range(steps)] self._path = QPainterPath() self._path.addRoundedRect(0, 0, 4, 2, 1, 1) def start(self): self.animationTimer = QTimer(self) self.connect(self.animationTimer, SIGNAL("timeout()"), self.run) self.animationTimer.start(35) self._isRunning = True def stop(self): if self.animationTimer is not None: self.animationTimer.stop() self.animationTimer = None self._isRunning = False self.repaint() def run(self): self.repaint() self._fillsteps = self._fillsteps[1:] + [self._fillsteps[0]] def paintEvent(self, event): if self._isRunning: anglestep = 360. / self._steps fillsteps = self._fillsteps factor = min(self.width(), self.height()) / 16. bw = self._bw p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) p.scale(factor, factor) p.setPen(Qt.NoPen) for i in range(self._steps): x1, y1 = self._coords[i] c = fillsteps[self._steps - 1 - i] a = anglestep * i p.setBrush(QBrush(QColor.fromRgbF(bw, bw, bw, c))) p.save() p.translate(x1 - 2, y1 - 1) p.translate(2, 1) p.rotate(a) p.translate(-2, -1) p.drawPath(self._path) p.restore()
class Hints(QGraphicsItem): def __init__(self, x_offset, y_offset): super(Hints, self).__init__() self.x_offset = x_offset self.y_offset = y_offset self.path = None self.setup_display() def setup_display(self, step=0): steps = ["Press Alt: matching commits mode", "Keep pressing Alt and hover over a commit", "That way you can see all the commits that have the same name"] self.path = QPainterPath() self.font = QFont() self.font.setFamily("Helvetica") self.font.setPointSize(FONT_SIZE) self.path.addText( self.x_offset, self.y_offset, self.font, QString(steps[step])) def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, painter, option, widget=None): painter.setPen(Qt.NoPen) painter.setBrush(QBrush(BLACK)) painter.drawPath(self.path)
def shape(self): if self._rect is not None: p = QPainterPath() p.addRect(self.boundingRect()) return p else: return super().shape()
def mouseMoveEvent(self, event): """ Normally our base class (QGraphicsScene) distributes mouse events to the various QGraphicsItems in the scene. But when the mouse is being dragged, it only sends events to the one object that was under the mouse when the button was first pressed. Here, we forward all events to QGraphicsItems on the drag path, even if they're just brushed by the mouse incidentally. """ super(ImageScene2D, self).mouseMoveEvent(event) if not event.isAccepted() and event.buttons() != Qt.NoButton: if self.last_drag_pos is None: self.last_drag_pos = event.scenePos() # As a special feature, find the item and send it this event. path = QPainterPath(self.last_drag_pos) path.lineTo(event.scenePos()) items = self.items(path) for item in items: item.mouseMoveEvent(event) self.last_drag_pos = event.scenePos() else: self.last_drag_pos = None
def draw_into(self, scene, incremental=False): for subbranch in self.branches: subbranch.draw_into(scene, incremental) start = self.already_drawn if incremental else None points = [QPointF(np.real(x), -np.imag(x)) for x in self.history[start:]] gens = float(self.params["painter_generations"]) scale_factor = (self.params["scale"] - 1) * 3 + 1 pen_width = max(0, gens-self.generation) / gens * self.params["painter_thickness"] * scale_factor if self.generation == 0 and len(self.history) < 30: intensity = 126/30.0 * len(self.history) else: intensity = 17 + 99 * max(0, gens-self.generation) / gens color = self.params["color"].darker(85 + (127 - intensity) * 4) outline = color.darker(500) pen = QPen(color) pen.setWidthF(pen_width) darkPen = QPen(outline) darkPen.setWidthF(pen_width) depth = self.params["depth"] path = QPainterPath() path.moveTo(points[0]) for index in range(1, len(points) - 1): path.lineTo(points[index]) scene.addPath(path, pen) if incremental: self.already_drawn = max(0, len(self.history) - 1)
def __updateCurve(self): self.prepareGeometryChange() if self.sourceAnchor and self.sinkAnchor: source_pos = self.sourceAnchor.anchorScenePos() sink_pos = self.sinkAnchor.anchorScenePos() source_pos = self.curveItem.mapFromScene(source_pos) sink_pos = self.curveItem.mapFromScene(sink_pos) # Adaptive offset for the curve control points to avoid a # cusp when the two points have the same y coordinate # and are close together delta = source_pos - sink_pos dist = math.sqrt(delta.x() ** 2 + delta.y() ** 2) cp_offset = min(dist / 2.0, 60.0) # TODO: make the curve tangent orthogonal to the anchors path. path = QPainterPath() path.moveTo(source_pos) path.cubicTo(source_pos + QPointF(cp_offset, 0), sink_pos - QPointF(cp_offset, 0), sink_pos) self.curveItem.setPath(path) self.sourceIndicator.setPos(source_pos) self.sinkIndicator.setPos(sink_pos) self.__updateText() else: self.setHoverState(False) self.curveItem.setPath(QPainterPath())
def toQPainterPath(self): """Return a QPainterPath containing all segments of this path. """ if not self.isValid(): raise Path2dException('invalid path') p = QPainterPath() sx, sy = self._elements[0] if len(self._elements[1]) == 2: # Only add a start point if the QPainterPath will start with a # line, not an arc. p.moveTo(sx, sy) for e in self._elements[1:]: if len(e) == 2: p.lineTo(*e) sx, sy = e else: (ex, ey), (cx, cy), arcDir = e r = hypot(ex - cx, ey - cy) d = r * 2 sa = degrees(atan2(sy - cy, sx - cx)) % 360.0 ea = degrees(atan2(ey - cy, ex - cx)) % 360.0 # NOTE: machtool uses a right-handed cartesian coordinate # system with the Y+ up. Because of this, the QRectF # used to define the arc has a negative height. This # makes a positive arc angle sweep cclw as it should. rect = QRectF(cx - r, cy + r, d, -d) if arcDir == 'cclw': span = (ea + 360.0 if ea < sa else ea) - sa else: span = -((sa + 360.0 if sa < ea else sa) - ea) p.arcMoveTo(rect, sa) p.arcTo(rect, sa, span) sx, sy = ex, ey return p
def __init__(self, parent, *args): GraphicsPathObject.__init__(self, parent, *args) self.setAcceptHoverEvents(True) self.setPen(QPen(Qt.NoPen)) self.normalBrush = QBrush(QColor("#CDD5D9")) self.connectedBrush = QBrush(QColor("#9CACB4")) self.setBrush(self.normalBrush) self.shadow = QGraphicsDropShadowEffect(blurRadius=10, color=QColor(SHADOW_COLOR), offset=QPointF(0, 0)) self.setGraphicsEffect(self.shadow) self.shadow.setEnabled(False) # Does this item have any anchored links. self.anchored = False if isinstance(parent, NodeItem): self.__parentNodeItem = parent else: self.__parentNodeItem = None self.__anchorPath = QPainterPath() self.__points = [] self.__pointPositions = [] self.__fullStroke = None self.__dottedStroke = None self.__shape = None
def __init_corner(self): path = QPainterPath() path.moveTo(-Block.padding, -15 - Block.padding) path.lineTo(-15 - Block.padding, -Block.padding) path.lineTo(-Block.padding, -Block.padding) path.closeSubpath() self.__corner_path = path
def __drawLine(self, painter, graph, width, height): path = QPainterPath() try: day = graph[0][0].day value = graph[0][0].data(self.__index) (x, y) = self.__getCoordinates(width, height, day, value) path.moveTo(x, y) except IndexError: pass for pos in range(1, len(graph[0])): point = graph[0][pos] day = point.day value = point.data(self.__index) (x, y) = self.__getCoordinates(width, height, day, value) path.lineTo(x, y) pen = QPen() pen.setColor(QColor(graph[2])) pen.setWidth(3) pen.setCapStyle(Qt.RoundCap); pen.setJoinStyle(Qt.RoundJoin); painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(path)
def generateArrows(self): x, y = self.size().width() - 4, self.size().height() - 4 pen = QtGui.QPen(QtGui.QColor(QtCore.Qt.black)) brush = QtGui.QBrush(pen.color().darker(150)) points_list = [[ QtCore.QPoint(x / 2, 0), QtCore.QPoint(x / 2 + 5, 5), QtCore.QPoint(x / 2 - 5, 5) ], [ QtCore.QPoint(x / 2, y), QtCore.QPoint(x / 2 + 5, y - 5), QtCore.QPoint(x / 2 - 5, y - 5) ], [ QtCore.QPoint(0, y / 2), QtCore.QPoint(5, y / 2 + 5), QtCore.QPoint(5, y / 2 - 5) ], [ QtCore.QPoint(x, y / 2), QtCore.QPoint(x - 5, y / 2 + 5), QtCore.QPoint(x - 5, y / 2 - 5) ]] for points in points_list: poly = QtGui.QPolygonF(points) path = QPainterPath() path.addPolygon(poly) self.rArrow = self.scene().addPolygon(poly, pen) self.scene().addPath(path, pen, brush)
def __init__(self, parent, pos, angle): Sector.__init__(self, parent, pos, angle) self.setZValue(1) path = QPainterPath() path.lineTo(_pitDistance, 0) self.setPath(path) self.setPen(QPen(_pitColor, _pitWidth))
def tick_DC(self, u, i): self.datau.pop(0) self.datai.pop(0) self.datau.append(u) self.datai.append(i) self.scene1 = QGraphicsScene() self.scene2 = QGraphicsScene() self.setup_scene(self.scene1) self.setup_scene(self.scene2) self.scene1.addSimpleText('[U/V]').moveBy(-39, 220-10) self.scene2.addSimpleText('[I/mA]').moveBy(-39, 220-10) self.scene1.addSimpleText('+4.0').moveBy(-40, 0-10) self.scene1.addSimpleText('+2.0').moveBy(-40, 50-10) self.scene1.addSimpleText(' 0.0').moveBy(-40, 100-10) self.scene1.addSimpleText('-2.0').moveBy(-40, 150-10) self.scene1.addSimpleText('-4.0').moveBy(-40, 200-10) self.scene2.addSimpleText('+0.4').moveBy(-40, 0-10) self.scene2.addSimpleText('+0.2').moveBy(-40, 50-10) self.scene2.addSimpleText(' 0.0').moveBy(-40, 100-10) self.scene2.addSimpleText('-0.2').moveBy(-40, 150-10) self.scene2.addSimpleText('-0.4').moveBy(-40, 200-10) path = QPainterPath() path.moveTo(0,100-self.datau[0]*25) for i in xrange(1,200): path.lineTo(3*(i+1), 100-self.datau[i]*25) self.scene1.addPath(path, QPen(QColor(0,0,255), 3)) path = QPainterPath() path.moveTo(0,100-self.datai[0]*25) for i in xrange(1,200): path.lineTo(3*(i+1), 100-self.datai[i]*25) self.scene2.addPath(path, QPen(QColor(0,0,255), 3)) self.ui.graph1.setScene(self.scene1) self.ui.graph2.setScene(self.scene2)
def __call__(o, gridfunc, piece_count, image_width, image_height): p = QPainterPath(QPointF(0.0, 0.0)) p.lineTo(QPointF(image_width, 0.0)) p.lineTo(QPointF(image_width, image_height)) p.lineTo(QPointF(0.0, image_height)) p.closeSubpath() o._boundary_path = p gridfunc(o, piece_count, image_width, image_height)
def path_for(points): path = QPainterPath(points[0]) for point in points[1:]: path.lineTo(point) path.lineTo(points[-1].x(), 0) path.lineTo(points[0].x(), 0) path.lineTo(points[0]) return path
def compute_path(self): p1 = self.p1 if self.p1.x() < self.p2.x() else self.p2 p2 = self.p2 if self.p1.x() < self.p2.x() else self.p1 path = QPainterPath() path.moveTo(p1) dx = p2.x() - p1.x() path.cubicTo(QPoint(p1.x() + dx / 3, p1.y()), QPoint(p2.x() - dx / 3, p2.y()), p2) self.__path = path
def test_shapeFromPath(self): path = QPainterPath() path.addRect(10, 10, 20, 20) pen = QPen(QColor("#FFF"), 2.0) path = shapeFromPath(path, pen) self.assertGreaterEqual(area(path.controlPointRect()), (20 + 2.0)**2)
def __init__(self, parent=None, **kwargs): QGraphicsObject.__init__(self, parent, **kwargs) self.setFlag(QGraphicsObject.ItemSendsGeometryChanges) self.__path = QPainterPath() self.__brush = QBrush(Qt.NoBrush) self.__pen = QPen() self.__boundingRect = None
def shape(self): """ Returns the shape used for selection """ s = QPainterPath() s.addPath(self.hexagon_path) if self.editable: s.addPath(self.stroke) return s
def test_shapeFromPath(self): path = QPainterPath() path.addRect(10, 10, 20, 20) pen = QPen(QColor("#FFF"), 2.0) path = shapeFromPath(path, pen) self.assertGreaterEqual(area(path.controlPointRect()), (20 + 2.0) ** 2)
def redraw_path(self): self.path = QPainterPath() for segment in self.segment(self.data()): if self.fitted: self.draw_cubic_path(segment) else: self.draw_normal_path(segment) self._item.setPath(self.graph_transform().map(self.path)) self._item.setPen(self.pen())
def _setup(self): steps = self._steps anglestep = 360. / steps fillstep = 0.6 / (steps - 1) self._fillsteps = [0.71 - i * fillstep for i in range(steps)] self._coords = [ coordinates(8, 8, 6, anglestep * i) for i in range(steps) ] self._path = QPainterPath() self._path.addRoundedRect(0, 0, 4, 2, 1, 1)
def __init_corner(self): path = QPainterPath() dpi = Info.dpi path.moveTo(-OIBlock.padding * 1.2 * dpi, (-.15 - OIBlock.padding * 1.2) * dpi) path.lineTo((-.15 - OIBlock.padding * 1.2) * dpi, -OIBlock.padding * 1.2 * dpi) path.lineTo(-OIBlock.padding * 1.2 * dpi, -OIBlock.padding * 1.2 * dpi) path.closeSubpath() self.__corner_path = path
def setShapeRect(self, rect): """ Set the item's shape `rect`. The item should be confined within this rect. """ path = QPainterPath() path.addEllipse(rect) self.setPath(path) self.__shapeRect = rect
def _paintPolygon(self, painter, polygon): path = QPainterPath() for line in polygon: ring = QPolygonF() for point in line: cur = self.toCanvasCoordinates(point) - self.pos() ring.append(cur) ring.append(ring[0]) path.addPolygon(ring) painter.drawPath(path)
def shape(self): params = parameters.instance path = QPainterPath() scale = self.scale half_size = params.old_point_size / 2. path.moveTo(0, -half_size * scale[1]) path.lineTo(0, half_size * scale[1]) path.moveTo(-half_size * scale[0], 0) path.lineTo(half_size * scale[0], 0) return path
def paint(self, painter, option, widget): params = parameters.instance pen = QPen(QColor(Qt.black)) scale = self.scale ms = min(scale) pen.setWidth(params.cell_thickness) sel_thick = 2*params.cell_thickness if sel_thick == 0: sel_thick = 2*ms col = None if self.current: col = QColor(params.selected_cell_color) elif self.hover: col = QColor(params.cell_hover_color) else: col = QColor(params.cell_color) painter.setBrush(col) if self.hover_contour: pen1 = QPen(QColor(Qt.white)) pen1.setWidth(sel_thick) painter.setPen(pen1) else: painter.setPen(pen) if isinstance(self.polygon, QPolygonF): painter.drawPolygon(self.polygon_shape) elif isinstance(self.polygon, QLineF): painter.drawLine(self.polygon) pen.setWidth(0) painter.setPen(pen) painter.drawPolygon(self.hexagon) if self.hover_side is not None: pen = QPen(QColor(Qt.red)) pen.setWidth(sel_thick) side = self.sides[self.hover_side] painter.setPen(pen) pp = QPainterPath() pp.moveTo(side[0]) for p in side[1:]: pp.lineTo(p) painter.drawPath(pp) elif self.division_line is not None: pen = QPen(params.division_wall_color) pen.setWidth(sel_thick) painter.setPen(pen) painter.drawLine(self.division_line) elif self.dragging_line: pen = QPen(QColor(Qt.red)) pen.setWidth(sel_thick) painter.setPen(pen) polygon = self.polygon dg = self.drag_side p1 = polygon[dg] p2 = polygon[dg+1] painter.drawLine(p1, self.moving_point) painter.drawLine(self.moving_point, p2)
def rebuild(self, gridRect): """ Rebuilds the tracker item. """ scene = self.scene() if (not scene): return self.setVisible(gridRect.contains(self.pos())) self.setZValue(100) path = QPainterPath() path.moveTo(0, 0) path.lineTo(0, gridRect.height()) tip = '' tip_point = None self._ellipses = [] items = scene.collidingItems(self) self._basePath = QPainterPath(path) for item in items: item_path = item.path() found = None for y in range(int(gridRect.top()), int(gridRect.bottom())): point = QPointF(self.pos().x(), y) if (item_path.contains(point)): found = QPointF(0, y - self.pos().y()) break if (found): path.addEllipse(found, 6, 6) self._ellipses.append(found) # update the value information value = scene.valueAt(self.mapToScene(found)) tip_point = self.mapToScene(found) hruler = scene.horizontalRuler() vruler = scene.verticalRuler() x_value = hruler.formatValue(value[0]) y_value = vruler.formatValue(value[1]) tip = '<b>x:</b> %s<br/><b>y:</b> %s' % (x_value, y_value) self.setPath(path) self.setVisible(True) # show the popup widget if (tip): anchor = XPopupWidget.Anchor.RightCenter widget = self.scene().chartWidget() tip_point = widget.mapToGlobal(widget.mapFromScene(tip_point)) XPopupWidget.showToolTip(tip, anchor=anchor, parent=widget, point=tip_point, foreground=QColor('blue'), background=QColor(148, 148, 255))
def __init__(self, radiusOut, raiusIn, angle, arcLen, parent=None): QGraphicsPathItem.__init__(self, parent=parent) self._radiusOut = radiusOut self._raiusIn = raiusIn self._angle = angle self._arcLen = arcLen self._pen = QPen(QColor('#000000')) self._pen.setWidth(1) self.setPen(self._pen) self._hoverPen = QPen(QColor('#000000')) self._hoverPen.setWidth(2) brush = QBrush(QColor('#FF9966')) self.setBrush(brush) rectOut = QRectF(-radiusOut, -radiusOut, radiusOut*2.0, radiusOut*2.0) rectIn = QRectF(-raiusIn, -raiusIn, raiusIn*2.0, raiusIn*2.0) startAngle = angle - arcLen/2.0 endAngle = angle + arcLen/2.0 path = QPainterPath() path.arcMoveTo(rectIn, startAngle) path.arcTo(rectOut, startAngle, arcLen) path.arcTo(rectIn, endAngle, 0) path.arcTo(rectIn, endAngle, -arcLen) self.setPath(path) self._isHover = False self._ioDragFirstPos = None
def __init__(self, parent, pos, angle, pit=False): QGraphicsItemGroup.__init__(self, parent) AbstractSector.__init__(self, pos, angle) self.setZValue(3) self.black = QGraphicsPathItem(self) self.white = QGraphicsPathItem(self) start = 3 * (_trackWidth / 2) end = -start - abs(_pitDistance if pit else 0) rowdelta = _trackWidth / 4 for item, y in [(self.black, -rowdelta), (self.white, rowdelta)]: item.setCacheMode(QGraphicsPathItem.DeviceCoordinateCache) self.addToGroup(item) path = QPainterPath() path.moveTo(start, y) path.lineTo(end, y) path.moveTo(end, -y) path.lineTo(start, -y) item.setPath(path) pen = QPen(Qt.black, _trackWidth / 2) pen.setCapStyle(Qt.FlatCap) pen.setDashPattern([1, 1]) self.black.setPen(QPen(pen)) pen.setColor(Qt.white) self.white.setPen(pen)
def toQPainterPath(self): """Return a QPainterPath containing all segments of this path. """ if not self.isValid(): raise Path2dException('invalid path') p = QPainterPath() sx, sy = self._elements[0] if len(self._elements[1]) == 2: # Only add a start point if the QPainterPath will start with a # line, not an arc. p.moveTo(sx, sy) for e in self._elements[1:]: if len(e) == 2: p.lineTo(*e) sx, sy = e else: (ex, ey), (cx, cy), arcDir = e r = hypot(ex-cx, ey-cy) d = r*2 sa = degrees(atan2(sy-cy, sx-cx)) % 360.0 ea = degrees(atan2(ey-cy, ex-cx)) % 360.0 # NOTE: machtool uses a right-handed cartesian coordinate # system with the Y+ up. Because of this, the QRectF # used to define the arc has a negative height. This # makes a positive arc angle sweep cclw as it should. rect = QRectF(cx - r, cy + r, d, -d) if arcDir == 'cclw': span = (ea + 360.0 if ea < sa else ea) - sa else: span = -((sa + 360.0 if sa < ea else sa) - ea) p.arcMoveTo(rect, sa) p.arcTo(rect, sa, span) sx, sy = ex, ey return p
def _updatePath(self): p0 = self._p0 p1 = self._p1 path = QPainterPath() path.moveTo(p0) dx = p1.x() - p0.x() x0 = p0.x() + 0.7 * dx x1 = p1.x() - 0.7 * dx path.cubicTo(QPointF(x0, p0.y()), QPointF(x1, p1.y()), p1) self.setPath(path)
def __init__(self, parent, pos, angle, length, color, radius, pit=False): PhysicalSector.__init__(self, parent, pos, angle, length, color, pit) self.angle = 180.0 * self.length() / (math.pi * radius) startAngle = 180.0 if radius > 0 else 0 offset = _pitDistance if pit else 0 radius -= offset rect = QRectF(offset + (2 * radius if radius < 0 else 0), -abs(radius), 2 * abs(radius), 2 * abs(radius)) path = QPainterPath(QPointF(offset, 0)) path.arcTo(rect, startAngle, self.angle) self.setPath(path)
def paint(self, painter, styleoptions, widget=None): try: width, realsize, label, fontsize = self._calc_size() except ZeroDivisionError: return mapunits = self.canvas.mapUnits() # painter.drawRect(self.boundingRect()) array = QPolygon() canvasheight = self.canvas.height() canvaswidth = self.canvas.width() margin = 20 originy = 0 originx = 0 self.setPos(margin, canvasheight - margin) x1, y1 = originx, originy x2, y2 = originx, originy + self.ticksize x3, y3 = originx + width, originy + self.ticksize midx, midy = originx + width /2, originy + self.ticksize / 2 x4, y4 = originx + width, originy for pen in self.pens: painter.setPen(pen) # Drwa the scale bar painter.drawLine(x1, y1, x2, y2) painter.drawLine(x2, y2, x3, y3) painter.drawLine(x3, y3, x4, y4) painter.drawLine(midx, midy, midx, y1) # Draw the text fontwidth = self.metrics.width("0") fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 path = QPainterPath() point = QPointF(x1 - fontwidth, y1 - fontheight) path.addText(point, self.font, "0") painter.setPen(self.whitepen) painter.setBrush(self.blackbrush) painter.setRenderHints(QPainter.Antialiasing) painter.setFont(self.font) painter.drawPath(path) fontwidth = self.metrics.width(label) fontheight = self.metrics.height() fontheight /= 2 fontwidth /= 2 point = QPointF(x4 - fontwidth, y4 - fontheight) path.addText(point, self.font, label) painter.drawPath(path)
def mouseMoveEvent(self, ev): super(SfGraphicsScene, self).mouseMoveEvent(ev) #clicked on empty space and moving if self._rubberHand is not None: self._rubberHand.setGeometry(QRect(self._rubberHandOrigin, ev.scenePos().toPoint()).normalized()) selectionArea = QPainterPath() selectionArea.addRect(QRectF(self._rubberHand.geometry())) self.setSelectionArea(selectionArea) if self.isDrawMode() and ev.buttons() == Qt.LeftButton and self._newLine is not None: line = self._newLine.line() line.setP2(ev.scenePos()) self._newLine.setLine(line) self._newLine.setStartPoint()
def paintEvent(self, QPaintEvent): p = QPainter(self.viewport()) clipPath = QPainterPath() clipPath.addEllipse(0, 0, 100, 100) p.setRenderHint(QPainter.Antialiasing) p.setClipPath(clipPath) p.setClipping(False) p.setPen(Qt.gray) p.drawPath(clipPath) self.update()
def test_layout(self): file_desc, disc_desc, bayes_desc = self.widget_desc() file_item = NodeItem() file_item.setWidgetDescription(file_desc) file_item.setPos(0, 150) self.scene.add_node_item(file_item) bayes_item = NodeItem() bayes_item.setWidgetDescription(bayes_desc) bayes_item.setPos(200, 0) self.scene.add_node_item(bayes_item) disc_item = NodeItem() disc_item.setWidgetDescription(disc_desc) disc_item.setPos(200, 300) self.scene.add_node_item(disc_item) link = LinkItem() link.setSourceItem(file_item) link.setSinkItem(disc_item) self.scene.add_link_item(link) link = LinkItem() link.setSourceItem(file_item) link.setSinkItem(bayes_item) self.scene.add_link_item(link) layout = AnchorLayout() self.scene.addItem(layout) self.scene.set_anchor_layout(layout) layout.invalidateNode(file_item) layout.activate() p1, p2 = file_item.outputAnchorItem.anchorPositions() self.assertTrue(p1 > p2) self.scene.node_item_position_changed.connect(layout.invalidateNode) path = QPainterPath() path.addEllipse(125, 0, 50, 300) def advance(): t = time.clock() bayes_item.setPos(path.pointAtPercent(t % 1.0)) disc_item.setPos(path.pointAtPercent((t + 0.5) % 1.0)) self.singleShot(20, advance) advance() self.app.exec_()
def test_graphicspathobject(self): obj = GraphicsPathObject() path = QPainterPath() obj.setFlag(GraphicsPathObject.ItemIsMovable) path.addEllipse(20, 20, 50, 50) obj.setPath(path) self.assertEqual(obj.path(), path) self.assertTrue(obj.path() is not path, msg="setPath stores the path not a copy") brect = obj.boundingRect() self.assertTrue(area(brect) == 50**2) with self.assertRaises(TypeError): obj.setPath("This is not a path") brush = QBrush(QColor("#ffbb11")) obj.setBrush(brush) self.assertEqual(obj.brush(), brush) self.assertTrue(obj.brush() is not brush, "setBrush stores the brush not a copy") pen = QPen(QColor("#FFFFFF"), 1.4) obj.setPen(pen) self.assertEqual(obj.pen(), pen) self.assertTrue(obj.pen() is not pen, "setPen stores the pen not a copy") brect = obj.boundingRect() self.assertGreaterEqual(area(brect), (50 + 1.4 * 2)**2) self.assertIsInstance(obj.shape(), QPainterPath) positions = [] obj.positionChanged[QPointF].connect(positions.append) pos = QPointF(10, 10) obj.setPos(pos) self.assertEqual(positions, [pos]) self.scene.addItem(obj) self.view.show() self.app.exec_()
def test_layout(self): file_desc, disc_desc, bayes_desc = self.widget_desc() file_item = NodeItem() file_item.setWidgetDescription(file_desc) file_item.setPos(0, 150) self.scene.add_node_item(file_item) bayes_item = NodeItem() bayes_item.setWidgetDescription(bayes_desc) bayes_item.setPos(200, 0) self.scene.add_node_item(bayes_item) disc_item = NodeItem() disc_item.setWidgetDescription(disc_desc) disc_item.setPos(200, 300) self.scene.add_node_item(disc_item) link = LinkItem() link.setSourceItem(file_item) link.setSinkItem(disc_item) self.scene.add_link_item(link) link = LinkItem() link.setSourceItem(file_item) link.setSinkItem(bayes_item) self.scene.add_link_item(link) layout = AnchorLayout() self.scene.addItem(layout) self.scene.set_anchor_layout(layout) layout.invalidateNode(file_item) layout.activate() p1, p2 = file_item.outputAnchorItem.anchorPositions() self.assertGreater(p1, p2) self.scene.node_item_position_changed.connect(layout.invalidateNode) path = QPainterPath() path.addEllipse(125, 0, 50, 300) def advance(): t = time.clock() bayes_item.setPos(path.pointAtPercent(t % 1.0)) disc_item.setPos(path.pointAtPercent((t + 0.5) % 1.0)) self.singleShot(20, advance) advance() self.app.exec_()
def test_graphicspathobject(self): obj = GraphicsPathObject() path = QPainterPath() obj.setFlag(GraphicsPathObject.ItemIsMovable) path.addEllipse(20, 20, 50, 50) obj.setPath(path) self.assertEqual(obj.path(), path) self.assertTrue(obj.path() is not path, msg="setPath stores the path not a copy") brect = obj.boundingRect() self.assertTrue(area(brect) == 50 ** 2) with self.assertRaises(TypeError): obj.setPath("This is not a path") brush = QBrush(QColor("#ffbb11")) obj.setBrush(brush) self.assertEqual(obj.brush(), brush) self.assertTrue(obj.brush() is not brush, "setBrush stores the brush not a copy") pen = QPen(QColor("#FFFFFF"), 1.4) obj.setPen(pen) self.assertEqual(obj.pen(), pen) self.assertTrue(obj.pen() is not pen, "setPen stores the pen not a copy") brect = obj.boundingRect() self.assertGreaterEqual(area(brect), (50 + 1.4 * 2) ** 2) self.assertIsInstance(obj.shape(), QPainterPath) positions = [] obj.positionChanged[QPointF].connect(positions.append) pos = QPointF(10, 10) obj.setPos(pos) self.assertEqual(positions, [pos]) self.scene.addItem(obj) self.view.show() self.app.exec_()
def draw_arc(x, y, radius_in, radius_out, angle_init, angle_end, painter): path = QPainterPath() path.moveTo(x + radius_in * cos(angle_init), y + radius_in * sin(angle_init)) path.arcTo(x - radius_out, y - radius_out, 2 * radius_out, 2 * radius_out, angle_init, angle_end - angle_init) path.arcTo(x - radius_in, y - radius_in, 2 * radius_in, 2 * radius_in, angle_end, angle_init - angle_end) path.closeSubpath() painter.drawPath(path)
def setPath(self, path): """Set the items `path` (:class:`QPainterPath`). """ if not isinstance(path, QPainterPath): raise TypeError("%r, 'QPainterPath' expected" % type(path)) if self.__path != path: self.prepareGeometryChange() # Need to store a copy of object so the shape can't be mutated # without properly updating the geometry. self.__path = QPainterPath(path) self.__boundingRect = None self.update()
def _updatePath(self): p0 = self._startPos p1 = self._endPos if p0 is None or p1 is None: return path = QPainterPath() path.moveTo(p0) dx = p1.x() - p0.x() x0 = p0.x() + 0.7 * dx x1 = p1.x() - 0.7 * dx path.cubicTo(QPointF(x0, p0.y()), QPointF(x1, p1.y()), p1) self.setPath(path)
def shape(self): params = parameters.instance path = QPainterPath() scale = self.scale half_size = params.old_point_size/2. path.moveTo(0, -half_size*scale[1]) path.lineTo(0, half_size*scale[1]) path.moveTo(-half_size*scale[0], 0) path.lineTo(half_size*scale[0], 0) return path
def drawArrow(self, paint, x1, y1, x2, y2): m = paint.worldMatrix() paint.translate(x1, y1) pi = 3.1415926 if abs(x2 - x1) > 0: alpha = math.atan(abs(y2 - y1) / abs(x2 - x1)) * 180 / pi else: alpha = 90 if y2 > y1: if x2 > x1: paint.rotate(alpha) else: paint.rotate(180 - alpha) else: if x2 > x1: paint.rotate(-alpha) else: paint.rotate(alpha - 180) endcoord = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) - self.size / 2 p1 = QPointF(endcoord, 0) paint.drawLine(0, 0, p1.x(), 0) coord = math.sqrt(9**2 - 6**2) p2 = QPointF(endcoord - coord, 6) p3 = QPointF(endcoord - coord, -6) path = QPainterPath() path.moveTo(p1) path.lineTo(p2) path.lineTo(p3) path.lineTo(p1) paint.fillPath(path, paint.pen().color()) paint.setWorldMatrix(m)
class DataPipe(QtDeclarative.QDeclarativeItem): def __init__(self, color): super(DataPipe, self).__init__() self.color = color self.sourcePoint = QPoint(0,0,0) self.destinationPoint = QPoint(0,0,0) self.rect = QRectF(0, -20, 30, 40) self.path = QPainterPath() self.change = 1 self.angle = 0 def setSourcePoint(self,srcp): self.sourcePoint = srcp def setDestinationPoint(self,dstp): self.destinationPoint = dstp def boundingRect(self): return self.path.boundingRect() def shape(self): return self.path def paint(self, painter, option, widget=None): painter.setPen(QPen(QColor(0,0,0))) painter.setBrush(QBrush(self.color)) painter.pen().setWidth(4); painter.setBrush(Qt.NoBrush); painter.drawPath(self.path); self.path.moveTo(sourcePoint); self.path.lineTo(self.destinationPoint); #self.path.cubicTo(cp1.x(),cp1.y(),cp2.x(),cp2.y(),destPoint.x(),destPoint.y()); painter.drawPath(self.path); def advance(self, phase): if phase == 0: matrix = self.matrix() matrix.reset() self.setMatrix(matrix) self.angle += self.change * random.random() if self.angle > 4.5: self.change = -1 self.angle -= 0.00001 elif self.angle < -4.5: self.change = 1 self.angle += 0.00001 elif phase == 1: self.rotate(self.angle)
def __init__(self, edge): QGraphicsPathItem.__init__(self) self.__edge = edge startPoint = QPointF(edge.points[0][0], edge.points[0][1]) painterPath = QPainterPath(startPoint) index = 1 while index + 3 <= len(edge.points): painterPath.cubicTo(edge.points[index][0], edge.points[index][1], edge.points[index + 1][0], edge.points[index + 1][1], edge.points[index + 2][0], edge.points[index + 2][1]) index = index + 3 if index + 2 <= len(edge.points): painterPath.quadTo(edge.points[index + 1][0], edge.points[index + 1][1], edge.points[index + 2][0], edge.points[index + 2][1]) index = index + 2 if index + 1 <= len(edge.points): painterPath.lineTo(edge.points[index + 1][0], edge.points[index + 1][1]) if edge.head != edge.tail: lastIndex = len(edge.points) - 1 self.addArrow(painterPath, edge.points[lastIndex - 1][0], edge.points[lastIndex - 1][1], edge.points[lastIndex][0], edge.points[lastIndex][1]) self.setPath(painterPath) return
def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: if self.__mode == PlotSelectionTool.Rect: rect = QRectF(event.buttonDownPos(Qt.LeftButton), event.pos()) self.__path = QPainterPath() self.__path.addRect(rect) else: self.__path.lineTo(event.pos()) self.selectionUpdated.emit(self.selectionShape()) self.__updategraphics() event.accept() return True else: return False
def __init__(self, edge, modObj): QGraphicsPathItem.__init__(self) self.__edge = edge self.__modObj = modObj startPoint = QPointF(edge.points[0][0], edge.points[0][1]) painterPath = QPainterPath(startPoint) index = 1 while index + 3 <= len(edge.points): painterPath.cubicTo(edge.points[index][0], edge.points[index][1], edge.points[index + 1][0], edge.points[index + 1][1], edge.points[index + 2][0], edge.points[index + 2][1]) index = index + 3 if index + 2 <= len(edge.points): painterPath.quadTo(edge.points[index + 1][0], edge.points[index + 1][1], edge.points[index + 2][0], edge.points[index + 2][1]) index = index + 2 if index + 1 <= len(edge.points): painterPath.lineTo(edge.points[index + 1][0], edge.points[index + 1][1]) self.setPath(painterPath) return
def button_at(self, mouse_pos): white_button = QPainterPath() white_button.addEllipse( QPointF(self.contentsRect().width() - 50, self.contentsRect().height() - 50), 35, 35) if white_button.contains(mouse_pos): return True, "W" black_button = QPainterPath() black_button.addEllipse(QPointF(self.contentsRect().width() - 50, 50), 35, 35) if black_button.contains(mouse_pos): return True, "B" return False, ""
def updatePosition(self, scene): path = QPainterPath() self.prepareGeometryChange() count = len(self._longitudes) if count > 0: x, y = scene.posFromLonLat(self._longitudes, self._latitudes) dx = x - x[0] dy = y - y[0] for i in range(1, count): path.lineTo(dx[i], dy[i]) self.setPos(x[0], y[0]) self.setPath(path)
def paintEvent(self, QPaintEvent): back = (numpy.ones((100, 200, 300)) * 0).astype(numpy.uint8) back[0:60, 0:60, 0:60] = 255 ol = (numpy.zeros((100, 200, 300))).astype(numpy.uint8) ol[0:99, 0:99, 0:99] = 120 ol[0:99, 120:140, 0:99] = 255 path = QPainterPath() path.addRect(20, 20, 60, 60) path.moveTo(0, 0) path.cubicTo(99, 0, 50, 50, 99, 99) path.cubicTo(0, 99, 50, 50, 0, 0) painter = QPainter(self) painter.fillRect(0, 0, 100, 100, Qt.Qt.red)
def Path_toQtPath(geom): p = QPainterPath() anchor, points = geom if len(points) > 1: p.moveTo(*points[0]) for (x, y) in points[1:]: p.lineTo(x, y) elif len(points) == 1: r = QRectF(0, 0, 1e-0, 1e-9) r.moveCenter(*points[0]) p.addRect(r) elif len(points) == 0: r = QRectF(0, 0, 1e-16, 1e-16) r.moveCenter(QPointF(*anchor)) p.addRect(r) return p
def __init__(self, parent=None, anchor=0, **kwargs): GraphicsPathObject.__init__(self, parent, **kwargs) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, False) self.setAcceptedMouseButtons(Qt.LeftButton) self.__constraint = 0 self.__constraintFunc = None self.__anchor = 0 self.__initialPosition = None self.setAnchor(anchor) path = QPainterPath() path.addEllipse(QRectF(-4, -4, 8, 8)) self.setPath(path) self.setBrush(QBrush(Qt.lightGray, Qt.SolidPattern))