def draw(self, painter, draw=True): if self.color is None: return if draw: painter.save() pen = QPen(QColor(self.color)) if self.stroke is not None: pen.setWidthF(self.stroke) if self.line_style is not None: if self.line_style in [Qt.SolidLine, Qt.DashLine, Qt.DashDotLine, Qt.DotLine, Qt.DashDotDotLine]: pen.setStyle(self.line_style) elif isinstance(self.line_style, list): pen.setStyle(Qt.CustomDashLine) pen.setDashPattern(self.line_style) painter.setPen(pen) painter.setOpacity(self.opacity) polyline_to_draw = self.translated(0, 0) if self.scale is not None and self.scale != 1: polyline_to_draw = self.__scaled() # print('mid rect_to_plot', rect_to_plot) if self.translation is not None: # rect_to_plot.setX(rect_to_plot.x()+self.translation.x()) # rect_to_plot.setY(rect_to_plot.y()+self.translation.y()) polyline_to_draw.translate(self.translation.x(), self.translation.y()) # painter.drawPolygon(polygon_to_draw) if self.theta is not None and self.theta != 0: painter.translate(polyline_to_draw.boundingRect().center()) painter.rotate(self.theta) painter.translate(-polyline_to_draw.boundingRect().center()) painter.drawPolyline(polyline_to_draw) painter.restore()
def create_axis(self): bounding_end = abs(self.dimension_analysis.bounding_rect[3]) bounding_start = abs(self.dimension_analysis.bounding_rect[2]) pen = QPen() pen.setWidthF(0.5) # horizontal line self.graph_zero[0] = self.position[0] + self.margin - self.line_extend self.graph_zero[1] = self.position[1] + bounding_start * self.height_multiplier + self.margin self.graph_end[0] = self.graph_zero[0] + self.content_width + self.line_extend self.graph_end[1] = self.graph_zero[1] line_item_horizontal = QGraphicsLineItem(self.graph_zero[0], self.graph_zero[1], self.graph_end[0], self.graph_end[1]) line_item_horizontal.setPen(pen) self.addToGroup(line_item_horizontal) center = (self.graph_zero[0] + self.line_extend), self.graph_zero[1] y_top = center[1] - (bounding_start*self.height_multiplier) y_bottom = center[1]+(bounding_end*self.height_multiplier) line_item_vertical = QGraphicsLineItem(center[0], y_top, center[0], y_bottom) line_item_vertical.setPen(pen) self.addToGroup(line_item_vertical) pen_thin = QPen() pen_thin.setWidthF(0.2) start_graph = center[1] - 10 while start_graph > center[1] - bounding_start * self.height_multiplier: line_item_horizontal = QGraphicsLineItem(self.graph_zero[0], start_graph, self.graph_end[0], start_graph) line_item_horizontal.setPen(pen_thin) line_item_horizontal.setZValue(-0.5) self.addToGroup(line_item_horizontal) start_graph -= 10 start_graph = center[1] + 10 while start_graph < center[1] + bounding_end * self.height_multiplier: line_item_horizontal = QGraphicsLineItem(self.graph_zero[0], start_graph, self.graph_end[0], start_graph) line_item_horizontal.setPen(pen_thin) line_item_horizontal.setZValue(-0.5) self.addToGroup(line_item_horizontal) start_graph += 10
def paintEvent(self, event: QPaintEvent) -> None: painter = QStylePainter(self) opt = QStyleOptionSlider() self.initStyleOption(opt) if self.tickPosition() != QSlider.NoTicks: x = 4 for i in range(self.minimum(), self.width(), x): if i % 5 == 0: h = 18 w = 1 z = 8 else: h = 7 w = 0.8 z = 15 pen = QPen(QColor('#444')) pen.setWidthF(w) painter.setPen(pen) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksAbove): y = self.rect().top() + z painter.drawLine(x, y, x, y + h) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksBelow): y = self.rect().bottom() - z painter.drawLine(x, y, x, y - h) x += 10 opt.subControls = QStyle.SC_SliderGroove painter.drawComplexControl(QStyle.CC_Slider, opt) opt.subControls = QStyle.SC_SliderHandle painter.drawComplexControl(QStyle.CC_Slider, opt)
def draw(self, p: QPainter, scale: float): p.save() if self.selected: pen = QPen(QColor("red")) pen.setWidthF(2) else: pen = QPen(QColor("black")) pen.setWidthF(1) pen.setCosmetic(True) p.setPen(pen) brush = QBrush(QColor("black")) brush.setStyle(Qt.Dense7Pattern) brush.setTransform(QTransform().scale(1 / scale, 1 / scale)) p.setBrush(brush) if self.v_support and self.h_support: p.drawRect( QRectF(self.x - self.radius, self.y - self.radius, self.radius * 2, self.radius * 2)) elif self.h_support: self.drawSupport(p, 3) elif self.v_support: self.drawSupport(p, 2) else: p.drawEllipse( QRectF(self.x - self.radius, self.y - self.radius, self.radius * 2, self.radius * 2)) p.drawLine(QPointF(self.x - 0.125, self.y), QPointF(self.x + 0.125, self.y)) p.drawLine(QPointF(self.x, self.y - 0.125), QPointF(self.x, self.y + 0.125)) p.restore()
def checkers_border_paint(obj, painter): """Здесь производится рисование фона, рамок и градуировки для шашечной доски""" from View import view_model pen = QPen() pen.setWidthF(obj.pen_width) pen.setColor(QColor(89, 65, 37)) painter.setPen(pen) painter.drawPixmap( QPointF(obj.cell_size * (1 - obj.indent_frame_from_border), obj.cell_size * (1 - obj.indent_frame_from_border)), QPixmap(view_model.FrameBorderColor), QRectF( QPointF(obj.cell_size * (1 - obj.indent_frame_from_border), obj.cell_size * (1 - obj.indent_frame_from_border)), QPointF( obj.cell_size * (obj.border_size + 1) + obj.cell_size * obj.indent_frame_from_border, obj.cell_size * (obj.border_size + 1) + obj.cell_size * obj.indent_frame_from_border))) painter.drawRect( QRectF( QPointF(obj.cell_size * (1 - obj.indent_frame_from_border), obj.cell_size * (1 - obj.indent_frame_from_border)), QPointF( obj.cell_size * (obj.border_size + 1) + obj.cell_size * obj.indent_frame_from_border, obj.cell_size * (obj.border_size + 1) + obj.cell_size * obj.indent_frame_from_border))) set_graduation(obj, painter)
def paintEvent(self, event): p = QPainter(self) p.setRenderHint(QPainter.Antialiasing, True) p.save() side = self.height() p.scale(side / 100.0, side / 100.0) width = 100 * self.width() height = 100 * self.height() width = 100.0 * self.width() / self.height() height = 100.0 pen = QPen(p.pen()) pen.setColor(QColor(32, 32, 32)) pen.setWidthF(6.0) p.setPen(pen) p.setBrush(Qt.black) p.drawRoundedRect(3, 3, width - 6, height - 6, 7, (7 * width) / height) w = (width - 2 * self.Y_OFFSET) / self.m_digits x = (self.m_digits - 1) * w h = height - 2 * self.Y_OFFSET c = self.m_value r = 0 for i in range(self.m_digits): r = c % 10 c = c // 10 rect = QRectF(x + self.X_OFFSET, self.Y_OFFSET, w, h) self.m_svg.render(p, "d{}".format(r), rect) x -= w p.restore()
def paintEvent(self, event: QPaintEvent) -> None: painter = QStylePainter(self) opt = QStyleOptionSlider() self.initStyleOption(opt) if self.tickPosition() != QSlider.NoTicks: x = 4 for i in range(self.minimum(), self.width(), x): if i % 5 == 0: h = 18 w = 1 z = 8 else: h = 7 w = 0.8 z = 15 pen = QPen(QColor('#444')) pen.setWidthF(w) painter.setPen(pen) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksAbove): y = self.rect().top() + z painter.drawLine(x, y, x, y + h) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksBelow): y = self.rect().bottom() - z painter.drawLine(x, y, x, y - h) x += 10 opt.subControls = QStyle.SC_SliderGroove painter.drawComplexControl(QStyle.CC_Slider, opt) for path in self._regions: brushcolor = QColor(150, 190, 78, 185) if self._regions.index(path) == self._regionSelected \ else QColor(237, 242, 255, 185) painter.setBrush(brushcolor) painter.setPen(Qt.NoPen) painter.drawPath(path) opt.subControls = QStyle.SC_SliderHandle painter.drawComplexControl(QStyle.CC_Slider, opt)
def labelLines(self, img: Optional[QPixmap], toSrc: bool): if not img or not self.lines: return None painter = QPainter() painter.begin(img) painter.setRenderHint(QPainter.Antialiasing, True) pen = QPen() pen.setCapStyle(Qt.RoundCap) font = QFont('Consolas') if toSrc: pen.setWidthF(config.lineWidth * self.ratioToSrc) font.setPointSizeF(config.fontSize * self.ratioToSrc) else: pen.setWidthF(config.lineWidth) font.setPointSizeF(config.fontSize) painter.setFont(font) for (indexA, indexB), color in self.lines.items(): isHighlight = indexA in self.highlightPoints and indexB in self.highlightPoints \ and (self.mode == LabelMode.AngleMode or self.mode == LabelMode.VerticalMode) pen.setColor(QColor.lighter(color) if isHighlight else color) painter.setPen(pen) A = self.points[indexA][0] B = self.points[indexB][0] srcA = self.getSrcPoint(A) srcB = self.getSrcPoint(B) labelPoint: QPointF if toSrc: painter.drawLine(srcA, srcB) labelPoint = static.getMidpoint(srcA, srcB) else: painter.drawLine(A, B) labelPoint = static.getMidpoint(A, B) painter.drawText(static.getDistanceShift(A, B, labelPoint), str(round(static.getDistance(srcA, srcB), 2))) painter.end()
def __init__(self, port_mode, port_type, parent): QGraphicsPathItem.__init__(self) self.setParentItem(parent) self.m_port_mode = port_mode self.m_port_type = port_type # Port position doesn't change while moving around line self.p_itemX = self.scenePos().x() self.p_itemY = self.scenePos().y() self.p_width = parent.getPortWidth() if port_type == PORT_TYPE_AUDIO_JACK: pen = QPen(canvas.theme.line_audio_jack, 2) elif port_type == PORT_TYPE_MIDI_JACK: pen = QPen(canvas.theme.line_midi_jack, 2) elif port_type == PORT_TYPE_MIDI_ALSA: pen = QPen(canvas.theme.line_midi_alsa, 2) elif port_type == PORT_TYPE_PARAMETER: pen = QPen(canvas.theme.line_parameter, 2) else: qWarning( "PatchCanvas::CanvasBezierLineMov({}, {}, {}) - invalid port type" .format(port_mode2str(port_mode), port_type2str(port_type), parent)) pen = QPen(Qt.black) pen.setCapStyle(Qt.FlatCap) pen.setWidthF(pen.widthF() + 0.00001) self.setPen(pen)
def paintEvent(self, e): """ 绘制背景 """ iconPixmap = self.iconPixmap px, py = self._pixPos_list[0] painter = QPainter(self) painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform) painter.setPen(Qt.NoPen) if self.isPressed: if not self.isSelected: brush = QBrush(QColor(162, 162, 162, 120)) pen = Qt.NoPen else: brush = QBrush(QColor(110, 110, 110, 100)) pen = QPen(QColor(255, 255, 255, 160)) pen.setWidthF(1.5) # 绘制圆环和背景色 self.__drawCircle(painter, pen, brush) # 更新图标大小和位置 iconPixmap = self.iconPixmap.scaled(self.iconPixmap.width() - 4, self.iconPixmap.height() - 4, Qt.KeepAspectRatio, Qt.SmoothTransformation) px, py = self._pixPos_list[1] else: if self.isSelected: pen = QPen(QColor(255, 255, 255, 100)) pen.setWidthF(1.4) self.__drawCircle(painter, pen, QBrush(QColor(0, 0, 0, 60))) # 鼠标进入时更换图标透明度 elif self.isEnter: painter.setOpacity(0.5) # 绘制图标 painter.drawPixmap(px, py, iconPixmap.width(), iconPixmap.height(), iconPixmap)
def addRandomGraph(self): n = 50 # number of points in graph xScale = (random.random() + 0.5) * 2 yScale = (random.random() + 0.5) * 2 xOffset = (random.random() - 0.5) * 4 yOffset = (random.random() - 0.5) * 10 r1 = (random.random() - 0.5) * 2 r2 = (random.random() - 0.5) * 2 r3 = (random.random() - 0.5) * 2 r4 = (random.random() - 0.5) * 2 x, y = [], [] for i in range(n): x.append((i / float(n) - 0.5) * 10.0 * xScale + xOffset) y.append((math.sin(x[i] * r1 * 5) * math.sin(math.cos(x[i] * r2) * r4 * 3) + r3 * math.cos(math.sin(x[i]) * r4 * 2)) * yScale + yOffset) self.customPlot.addGraph() self.customPlot.graph().setName( "New graph {}".format(self.customPlot.graphCount() - 1)) self.customPlot.graph().setData(x, y) self.customPlot.graph().setLineStyle(random.randint(1, 6)) if random.randint(0, 100) > 50: self.customPlot.graph().setScatterStyle( QCPScatterStyle(random.randint(1, 15))) graphPen = QPen() graphPen.setColor( QColor(random.randint(10, 255), random.randint(10, 255), random.randint(10, 255))) graphPen.setWidthF(random.random() * 2 + 1) self.customPlot.graph().setPen(graphPen) self.customPlot.replot()
def drawLine(self, p1: QPoint, p2: QPoint, color: QColor): pen = QPen(color) if color == self.CUTTED_LINE_COLOR: pen.setWidthF(1.8) self.scene.addLine(p1.x(), p1.y(), p2.x(), p2.y(), pen)
def paintEvent(self, event): epyqlib.widgets.abstractwidget.AbstractWidget.paintEvent(self, event) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.translate(self.width() / 2, self.height() / 2) diameter = self.dimension() - self.tweaked_thickness() radius = diameter / 2 rectangle = QRectF(-radius, -radius, diameter, diameter) maximum = max(abs(self.maximum), abs(self.minimum)) span_angle = self.angle_span * (self.value / maximum) if self.clockwise: span_angle = -span_angle pen = QPen() pen.setWidthF(self.tweaked_thickness()) pen.setCapStyle(Qt.RoundCap) pen.setColor(self.background_color) painter.setPen(pen) painter.drawEllipse(rectangle) pen.setColor(self.color) painter.setPen(pen) qt_span = arc_angle(span_angle) if qt_span == 0: qt_span = 1 painter.drawArc(rectangle, arc_angle(self.zero_angle), qt_span)
def labelPoints(self, img: Optional[QPixmap], toSrc: bool): if not img or not self.points: return None painter = QPainter() painter.begin(img) painter.setRenderHint(QPainter.Antialiasing, True) pen = QPen() pen.setCapStyle(Qt.RoundCap) font = QFont('Consolas') if toSrc: pen.setWidthF(config.pointWidth * self.ratioToSrc) font.setPointSizeF(config.fontSize * self.ratioToSrc) else: pen.setWidthF(config.pointWidth) font.setPointSizeF(config.fontSize) painter.setFont(font) for index, (point, color) in self.points.items(): labelPoint: QPointF if toSrc: pen.setColor(color) labelPoint = self.getSrcPoint(point) else: pen.setColor( color if index != self.highlightMoveIndex and index not in self.highlightPoints else QColor.lighter(color) ) labelPoint = point painter.setPen(pen) painter.drawPoint(labelPoint) painter.drawText(static.getIndexShift(labelPoint), str(index)) painter.end()
def __init__(self, radius: float, center_x: float, center_y: float, start_angle: float, end_angle: float, clockwise, line_width: float, line_color=Qt.black, fill_color=Qt.transparent): super().__init__() # The supporting rectangle if end_angle < start_angle: end_angle += 2 * math.pi start_angle = -start_angle end_angle = -end_angle shift = end_angle - start_angle if clockwise: shift = -shift - 2 * math.pi x, y = center_x - radius, center_y - radius self.rect = QRectF(x, y, 2 * radius, 2 * radius) # The underlying QGraphicsPathItem self.painter_path = QPainterPath( QPointF(center_x + math.cos(start_angle) * radius, center_y - math.sin(start_angle) * radius)) self.painter_path.arcTo(self.rect, math.degrees(start_angle), math.degrees(shift)) self.path = QGraphicsPathItem(self.painter_path) self.path.setBrush(QtGui.QBrush(fill_color)) pen = QPen() pen.setWidthF(line_width) pen.setColor(line_color) self.path.setPen(pen) self._visible = 1
def paint(self, painter, option, widget=None): # Draw header rect = QRectF(0, 0, 20, 20) if self.stage: brush = QBrush(self.on_color_1) else: brush = QBrush(self.off_color_1) pen = QPen() pen.setStyle(LINE_SOLID) pen.setWidthF(1) pen.setWidth(2) pen.setCapStyle(ROUND_CAP) pen.setJoinStyle(ROUND_JOIN) painter.setBrush(brush) painter.setPen(pen) painter.drawEllipse(-5, -5, 10, 10) if self.stage: brush = QBrush(self.on_color_2) else: brush = QBrush(self.off_color_2) painter.setBrush(brush) painter.setPen(pen) painter.drawEllipse(-7, -7, 14, 14)
def drawGlyphFillAndStroke( painter, glyph, scale, rect, drawFill=True, drawStroke=True, drawSelection=True, partialAliasing=True, contourFillColor=None, contourStrokeColor=None, componentFillColor=None, contourStrokeWidth=1.0, selectionColor=None): # get the layer color layer = glyph.layer layerColor = None if layer is not None and layer.color is not None: layerColor = colorToQColor(layer.color) if selectionColor is None: selectionColor = defaultColor("glyphSelection") # get the paths contourPath = glyph.getRepresentation("defconQt.NoComponentsQPainterPath") componentPath = glyph.getRepresentation( "defconQt.OnlyComponentsQPainterPath") try: selectionPath = glyph.getRepresentation( "defconQt.FilterSelectionQPainterPath") except: traceback.print_exc() selectionPath = QPainterPath() painter.save() # fill if drawFill: # contours if contourFillColor is None and layerColor is not None: contourFillColor = layerColor elif contourFillColor is None and layerColor is None: contourFillColor = defaultColor("glyphContourFill") painter.fillPath(contourPath, QBrush(contourFillColor)) # components if componentFillColor is None and layerColor is not None: componentFillColor = layerColor elif componentFillColor is None and layerColor is None: componentFillColor = defaultColor("glyphComponentFill") painter.fillPath(componentPath, QBrush(componentFillColor)) # selection if drawSelection: pen = QPen(selectionColor) pen.setWidthF(5.0 * scale) painter.setPen(pen) painter.drawPath(selectionPath) # stroke if drawStroke: # work out the color if contourStrokeColor is None and layerColor is not None: contourStrokeColor = layerColor elif contourStrokeColor is None and layerColor is None: contourStrokeColor = defaultColor("glyphContourStroke") # contours pen = QPen(contourStrokeColor) pen.setWidthF(contourStrokeWidth * scale) painter.setPen(pen) if partialAliasing: drawGlyphWithAliasedLines(painter, glyph) else: painter.drawPath(contourPath) painter.restore()
def change_color_all_links(self, the_color): for edge in self.graph_to_display.es: line = self.lines[edge.index] line.edge['edge_color'] = the_color line_pen = QPen(line.edge['edge_color']) line_pen.setWidthF(line.edge['edge_width']) line.setPen(line_pen) line._pen = line_pen
def shape(self): if self.__shape is None: path = self.path() pen = QPen(self.pen()) pen.setWidthF(max(pen.widthF(), 7.0)) pen.setStyle(Qt.SolidLine) self.__shape = stroke_path(path, pen) return self.__shape
def penForID(self, penId): pen = QPen() if penId == PenID.Axis: pen.setColor(Qt.darkGray) pen.setWidthF(self.LINE_WIDTH) elif penId == PenID.AxisOverlay: pen.setColor(Qt.darkGray) pen.setWidthF(self.OVERLAY_AXIS_WIDTH) return pen
def drawFocusRect(self, painter): """Highlight selected""" focus_brush = QBrush() focus_pen = QPen(Qt.DotLine) focus_pen.setColor(Qt.red) focus_pen.setWidthF(1.5) painter.setBrush(focus_brush) painter.setPen(focus_pen) painter.drawRect(self.focus_rect)
def paintEvent(self, event: QPaintEvent) -> None: painter = QStylePainter(self) opt = QStyleOptionSlider() self.initStyleOption(opt) font = painter.font() font.setPixelSize(10) painter.setFont(font) if self.tickPosition() != QSlider.NoTicks: x = 8 for i in range(self.minimum(), self.width(), 8): if i % 5 == 0: h = 18 w = 1 z = 13 else: h = 8 w = 1 z = 23 tickcolor = '#8F8F8F' if self.theme == 'dark' else '#444' pen = QPen(QColor(tickcolor)) pen.setWidthF(w) painter.setPen(pen) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksAbove): y = self.rect().top() + z painter.drawLine(x, y, x, y + h) if self.tickPosition() in (QSlider.TicksBothSides, QSlider.TicksBelow): y = self.rect().bottom() - z painter.drawLine(x, y, x, y - h) if self.parent.mediaAvailable and i % 15 == 0: painter.setPen(Qt.white if self.theme == 'dark' else Qt.black) timecode = QStyle.sliderValueFromPosition( self.minimum(), self.maximum(), x - self.offset, self.width() - (self.offset * 2)) timecode = self.parent.delta2QTime(timecode).toString( self.parent.runtimeformat) painter.drawText(x + 6, y + 6, timecode) if x + 30 > self.width(): break x += 15 opt.subControls = QStyle.SC_SliderGroove painter.drawComplexControl(QStyle.CC_Slider, opt) for rect in self._regions: rect.setY(int((self.height() - self._regionHeight) / 2) - 8) rect.setHeight(self._regionHeight) if self._regions.index(rect) == self._regionSelected: brushcolor = QColor(150, 190, 78, 185) else: brushcolor = QColor(237, 242, 255, 185) painter.setBrush(brushcolor) painter.setPen(QColor(255, 255, 255, 170)) painter.drawRect(rect) opt.subControls = QStyle.SC_SliderHandle painter.drawComplexControl(QStyle.CC_Slider, opt)
def drawGlyphFillAndStroke( painter, glyph, scale, rect, drawFill=True, drawStroke=True, drawSelection=True, partialAliasing=True, contourFillColor=None, contourStrokeColor=None, componentFillColor=None, contourStrokeWidth=1.0, selectionColor=None): # get the layer color layer = glyph.layer layerColor = None if layer is not None and layer.color is not None: layerColor = colorToQColor(layer.color) if selectionColor is None: selectionColor = defaultColor("glyphSelection") # get the paths contourPath = glyph.getRepresentation("defconQt.NoComponentsQPainterPath") componentPath = glyph.getRepresentation( "defconQt.OnlyComponentsQPainterPath") selectionPath = glyph.getRepresentation( "defconQt.FilterSelectionQPainterPath") painter.save() # fill if drawFill: # contours if contourFillColor is None and layerColor is not None: contourFillColor = layerColor elif contourFillColor is None and layerColor is None: contourFillColor = defaultColor("glyphContourFill") painter.fillPath(contourPath, QBrush(contourFillColor)) # components if componentFillColor is None and layerColor is not None: componentFillColor = layerColor elif componentFillColor is None and layerColor is None: componentFillColor = defaultColor("glyphComponentFill") painter.fillPath(componentPath, QBrush(componentFillColor)) # selection if drawSelection: pen = QPen(selectionColor) pen.setWidthF(5.0 * scale) painter.setPen(pen) painter.drawPath(selectionPath) # stroke if drawStroke: # work out the color if contourStrokeColor is None and layerColor is not None: contourStrokeColor = layerColor elif contourStrokeColor is None and layerColor is None: contourStrokeColor = defaultColor("glyphContourStroke") # contours pen = QPen(contourStrokeColor) pen.setWidthF(contourStrokeWidth * scale) painter.setPen(pen) if partialAliasing: drawGlyphWithAliasedLines(painter, glyph) else: painter.drawPath(contourPath) painter.restore()
class PenWidthSettable(object): def __init__(self): self._pen = QPen() @property def penWidth(self) -> float: return self._pen.widthF() @penWidth.setter def penWidth(self, newWidth: number) -> None: self._pen.setWidthF(newWidth)
def drawContents(self, painter): if self._to_stop: return painter.save() painter.setPen(QColor(255, 255, 255, 255)) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.Antialiasing, True) version = Application.getInstance().getVersion().split("-") # Draw version text font = QFont() # Using system-default font here font.setPixelSize(18) painter.setFont(font) painter.drawText( 60, 70 + self._version_y_offset, round(330 * self._scale), round(230 * self._scale), Qt.AlignLeft | Qt.AlignTop, version[0] if not ApplicationMetadata.IsAlternateVersion else ApplicationMetadata.CuraBuildType) if len(version) > 1: font.setPixelSize(16) painter.setFont(font) painter.setPen(QColor(200, 200, 200, 255)) painter.drawText(247, 105 + self._version_y_offset, round(330 * self._scale), round(255 * self._scale), Qt.AlignLeft | Qt.AlignTop, version[1]) painter.setPen(QColor(255, 255, 255, 255)) # Draw the loading image pen = QPen() pen.setWidthF(6 * self._scale) pen.setColor(QColor(32, 166, 219, 255)) painter.setPen(pen) painter.drawArc(60, 150, round(32 * self._scale), round(32 * self._scale), round(self._loading_image_rotation_angle * 16), 300 * 16) # Draw message text if self._current_message: font = QFont() # Using system-default font here font.setPixelSize(13) pen = QPen() pen.setColor(QColor(255, 255, 255, 255)) painter.setPen(pen) painter.setFont(font) painter.drawText(100, 128, 170, 64, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextWordWrap, self._current_message) painter.restore() super().drawContents(painter)
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 draw(image, wave1d, font): size = image.size() centerY = math.floor(size.height() / 2) qp = QPainter(image) qp.setRenderHints(QPainter.Antialiasing) qp.fillRect(0, 0, size.width(), size.height(), Qt.white) color = QColor(0x44, 0x88, 0xff) qp.setPen(color) qp.setBrush(color) wav = wave1d.value() path = QPainterPath() path.moveTo(0, centerY) denom = len(wav) - 1 for i in range(0, len(wav)): path.lineTo( size.width() * i / denom, centerY + wav[i], ) path.lineTo(size.width() + 1, size.height()) path.lineTo(0, size.height()) qp.drawPath(path) if wave1d.pickY != 0: pen = QPen(QColor(0xe0, 0x20, 0x10)) pen.setWidthF(2.0) pen.setCapStyle(Qt.RoundCap) qp.setPen(pen) w = 8 h = 16 centerX = size.width() / 2 - 0.5 depth = centerY + wave1d.pickY qp.drawLine(QPointF(centerX, centerY - h), QPointF(centerX, centerY)) qp.drawLine( QPointF(centerX - w / 2, centerY - h / 4), QPointF(centerX, centerY), ) qp.drawLine( QPointF(centerX + w / 2, centerY - h / 4), QPointF(centerX, centerY), ) qp.setPen(Qt.black) qp.setFont(font) line_space = QFontMetrics(font).lineSpacing() qp.drawText(4, 1 * line_space, " α={:0.3}".format(wave1d.alpha)) qp.drawText(4, 2 * line_space, " β={:0.3}".format(wave1d.beta)) qp.drawText(4, 3 * line_space, "τ_ε={:0.8}".format(wave1d.tau_epsilon)) qp.setPen(QColor(0x30, 0x30, 0x30)) qp.setBrush(Qt.transparent) qp.drawRect(0, 0, size.width(), size.height())
def steps_focus_draw(painter, checker): """Проихводится отрисовка зелёных обрамлений на доступных для простого хода клетках""" pen = QPen(QColor(78, 237, 42)) pen.setWidthF(2) painter.setPen(pen) for chain in logic.possible_cells_for_steps_or_hit(checker): for cell in chain: painter.drawRect(rect_coordinates_create(cell.border_coordinates))
def draw(self, painter, draw=True): if draw: painter.save() pen = QPen(QColor(self.color)) if self.stroke is not None: pen.setWidthF(self.stroke) painter.setPen(pen) painter.setOpacity(self.opacity) if draw: painter.drawLine(self) painter.restore()
def morph(self): lines = self.view.scene.lines scaled_value = (np.sin(self.INITIAL_VALUE + time.time() * 2) + 1) / 2 for line in lines: line_index = lines.index(line) line_pen = QPen( QColor(255 - scaled_value[line_index] * 255, 255 - scaled_value[line_index] * 255, scaled_value[line_index] * 255)) line_pen.setWidthF(line.edge['edge_width']) line.setPen(line_pen)
def __init__(self): self.chart = QChart() QChartView.__init__(self, self.chart) self.axisX = QValueAxis() self.axisY = QValueAxis() self.xRange = [0, 100] self.yRange = [-100, 100] self.curve = [] self.scatterCurve = [] self.setBackgroundBrush(QColor('#D8D8D8')) self.setRenderHint(QPainter.Antialiasing) self.chart.setAnimationOptions(QChart.NoAnimation) self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignBottom) self.chart.legend().setLabelColor(Qt.white) self.chart.legend().setMarkerShape(QLegend.MarkerShapeFromSeries) self.chart.setBackgroundBrush(QColor('#00004D')) penAxisGrid = QPen(QColor('#F2F2F2')) penAxisGrid.setWidthF(0.5) penAxisMinorGrid = QPen(QColor('#A4A4A4')) penAxisMinorGrid.setWidthF(0.3) self.axisX.setGridLinePen(penAxisGrid) self.axisX.setLinePen(penAxisGrid) self.axisY.setGridLinePen(penAxisGrid) self.axisY.setLinePen(penAxisGrid) self.axisX.setMinorGridLinePen(penAxisMinorGrid) self.axisY.setMinorGridLinePen(penAxisMinorGrid) self.axisX.setLabelsColor(Qt.white) self.axisY.setLabelsColor(Qt.white) self.axisX.setMinorTickCount(4) self.axisY.setMinorTickCount(4) self.axisX.setTitleBrush(Qt.white) self.axisY.setTitleBrush(Qt.white) self.axisX.setTitleText('Time') self.axisY.setTitleText('Signal Amplitude') self.axisX.setTickCount(11) self.axisY.setTickCount(11) self.axisX.setRange(self.xRange[0], self.xRange[1]) self.axisY.setRange(self.yRange[0], self.yRange[1])
def drawGlyphAnchors(painter, glyph, scale, rect, drawAnchors=True, drawSelection=True, drawText=True, color=None, selectionColor=None): if not glyph.anchors: return if color is None: color = defaultColor("glyphAnchor") if selectionColor is None: selectionColor = defaultColor("glyphSelection") fallbackColor = color anchorSize = 6 * scale anchorHalfSize = anchorSize / 2 for anchor in glyph.anchors: if anchor.color is not None: color = colorToQColor(anchor.color) else: color = fallbackColor x = anchor.x y = anchor.y name = anchor.name painter.save() if drawAnchors: path = QPainterPath() path.addEllipse(x - anchorHalfSize, y - anchorHalfSize, anchorSize, anchorSize) painter.fillPath(path, color) if drawSelection and anchor.selected: pen = QPen(selectionColor) pen.setWidthF(5.0 * scale) painter.setPen(pen) painter.drawPath(path) if drawText and name: painter.setPen(color) # TODO: we're using + before we shift to top, ideally this should # be abstracted w drawTextAtPoint taking a dy parameter that will # offset the drawing region from origin regardless of whether we # are aligning to top or bottom. y += 3 * scale drawTextAtPoint(painter, name, x, y, scale, xAlign="center", yAlign="top") painter.restore()
def elipse_adder(self, x, y): pen = QPen(QColor(69, 130, 201, 200)) # QColor(128, 128, 255, 128) pen.setWidthF(10) # border width brush = QBrush(Qt.transparent) elipse = self.addEllipse(x - 25, y - 25, 50, 50, pen, brush) elipse.setAcceptDrops(True) elipse.setCursor(Qt.OpenHandCursor) elipse.setFlag(QGraphicsItem.ItemIsSelectable, True) elipse.setFlag(QGraphicsItem.ItemIsMovable, True) elipse.setFlag(QGraphicsItem.ItemIsFocusable, True) elipse.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) elipse.setAcceptHoverEvents(True) self.circles.append(elipse)
def paint(self, painter, option, widget): if self.points is not None and self.drawLineFlag: painter.save() pen = QPen(self.color) pen.setWidthF(self.lineWidth) painter.setPen(pen) qPoints = [QPointF(*p.tolist()) for p in self.points if not np.isnan(p).any()] polygon = QPolygonF(qPoints) painter.drawPolyline(polygon) painter.restore()
def create_distance_pointer(self): self.distance_pointer = QGraphicsLineItem() pen = QPen() pen.setWidthF(1.0) pen.setStyle(Qt.DashDotLine) color = Color.create_qcolor_from_rgb_tuple_f((1,0,0)) pen.setColor(color) self.distance_pointer.setPen(pen) self.distance_pointer.setZValue(1.0) self.addToGroup(self.distance_pointer) self.distance_label = QGraphicsSimpleTextItem() self.distance_label.setZValue(1.0) self.addToGroup(self.distance_label)
def __init__(self, parent=None): ChartView.__init__(self, parent) self.dataSource = None pen = QPen() pen.setColor(QColor(20, 158, 11)) pen.setWidthF(self.LINE_WIDTH) self.linePen = pen gradient = QLinearGradient(0, 0, 0, 1) gradient.setCoordinateMode(QLinearGradient.ObjectBoundingMode) gradient.setColorAt(0, QColor(93, 188, 86)) # dark green gradient.setColorAt(1, QColor(164, 216, 158)) # light green self.graphBrush = QBrush(gradient) gradient = QLinearGradient(0, 0, 0, 1) gradient.setCoordinateMode(QLinearGradient.ObjectBoundingMode) gradient.setColorAt(0, Qt.darkGray) gradient.setColorAt(1, Qt.lightGray) self.graphFutureBrush = QBrush(gradient)
def paint(self, painter, option, widget): if self.data is not None and self.drawLineFlag: painter.save() key = str(self.currentFrameNo) if key in self.data.keys(): line_data = self.data[key] for line, color in zip(line_data, self.colors): pen = QPen(color) pen.setWidthF(self.lineWidth) painter.setPen(pen) qPoints = [QPointF(*p) for p in line] polygon = QPolygonF(qPoints) painter.drawPolyline(polygon) painter.restore()
def createPen(style=Qt.SolidLine, color='black', width=1): """ Use this function to conveniently create a cosmetic pen with specified width. Integer widths create cosmetic pens (default) and float widths create scaling pens (this way you can set the figure style by changing a number). This is particularly important on PyQt5 where the default pen blacks out large areas of the figure if not being careful. """ pen = QPen(style) pen.setColor(QColor(color)) if isinstance(width, int): pen.setWidth(width) pen.setCosmetic(True) else: pen.setWidthF(width) pen.setCosmetic(False) return pen
def drawGlyphImage(painter, glyph, scale, rect, selectionColor=None): image = glyph.image pixmap = image.getRepresentation("defconQt.QPixmap") if pixmap is None: return if selectionColor is None: selectionColor = defaultColor("glyphSelection") painter.save() painter.setTransform(QTransform(*image.transformation), True) painter.save() painter.translate(0, pixmap.height()) painter.scale(1, -1) painter.drawPixmap(0, 0, pixmap) painter.restore() if image.selected: pen = QPen(selectionColor) pen.setWidthF(5.0 * scale) painter.setPen(pen) painter.drawRect(pixmap.rect()) painter.restore()
def create_material_legend(self, *args): self.position = args[0], args[1] square_size = 20 material_list_key = sorted(self.material_dict) x_init = self.position[0] + self.left_margin y_init = self.position[1] + self.top_margin i = 0 for key in material_list_key: scene_y = y_init + i * (square_size + 5) material = self.material_dict[key] surface_colour = material.get_surface_colour() rect = QGraphicsRectItem(x_init, scene_y, square_size, square_size) pen = QPen() pen.setWidthF(0.5) rect.setPen(pen) BaseGraphic.set_rect_fill(self.visualization_mode, rect, surface_colour) self.graphic_items.append(rect) text = QGraphicsSimpleTextItem(key) text.setPos(x_init + square_size + 5, scene_y) self.graphic_items.append(text) i += 1
def create_axis(self): counter = 0 while self.surface[0][counter] is None: #get the first tile counter += 1 # determining the distance from left side left_coordinate = abs(self.surface[0][counter].point.X()) distance = (left_coordinate + counter * self.sampling_distance) * self.height_multiplier pen = QPen() pen.setWidthF(0.5) self.graph_zero[0] = self.position[0] + self.margin - self.line_extend self.graph_zero[1] = self.position[1] + distance + self.margin self.graph_end[0] = self.graph_zero[0] + self.content_width + self.line_extend self.graph_end[1] = self.graph_zero[1] line_item_horizontal = QGraphicsLineItem(self.graph_zero[0], self.graph_zero[1], self.graph_end[0], self.graph_end[1]) line_item_horizontal.setPen(pen) self.addToGroup(line_item_horizontal) center = (self.graph_zero[0] + self.line_extend), self.graph_zero[1] y_top = center[1] - distance y_bottom = self.position[1] + self.margin + len(self.surface[0]) * self.sampling_distance * self.height_multiplier line_item_vertical = QGraphicsLineItem(center[0], y_top, center[0], y_bottom) line_item_vertical.setPen(pen) self.addToGroup(line_item_vertical)
def paintEvent(self,event): global monster_data global dmg painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.drawPixmap(event.rect(),self.pixmap) if self.card is not None and self.card.ID is not 0: card = self.card # Draw card level at the bottom centered pen = QPen() if np.floor(card.lv) == monster_data[card.ID]['max_level']: lvstr = 'Lv.Max' brush = QBrush(QColor(252,232,131)) else: lvstr = 'Lv.%d' % np.floor(card.lv) brush = QBrush(Qt.white) path = QPainterPath() pen.setWidth(0); pen.setBrush(Qt.black) font = QFont() font.setPointSize(11) font.setWeight(QFont.Black) path.addText(event.rect().x(),event.rect().y()+48,font,lvstr) rect = path.boundingRect() target = (event.rect().x()+event.rect().width())/2 # center the rect in event.rect() path.translate(target-rect.center().x(), 0) painter.setPen(pen) painter.setBrush(QBrush(Qt.black)) painter.drawPath(path.translated(.5,.5)) painter.setPen(pen) painter.setBrush(brush) painter.drawPath(path) # Draw +eggs at the top right eggs = card.plus_atk+card.plus_hp+card.plus_rcv if eggs > 0: eggstr = '+%d' % eggs pen.setBrush(Qt.yellow) brush = QBrush(Qt.yellow) path = QPainterPath() pen.setWidth(0) pen.setBrush(Qt.black) font = QFont() font.setPointSize(11) font.setWeight(QFont.Black) path.addText(event.rect().x(),event.rect().y()+12,font,eggstr) path.translate(50-path.boundingRect().right()-3,0) #painter.setFont(font) painter.setPen(pen) painter.setBrush(QBrush(Qt.black)) painter.drawPath(path.translated(.5,.5)) painter.setPen(pen) painter.setBrush(brush) painter.drawPath(path) #painter.drawText(event.rect().adjusted(0,0,0,0),Qt.AlignRight, eggstr) # Draw awakenings at the top left in a green circle if card.current_awakening > 0: path = QPainterPath() rect = QRectF(event.rect()).adjusted(4,4,-36,-36) path.addEllipse(rect) painter.setBrush(QBrush(QColor(34,139,34))) pen.setBrush(Qt.white) pen.setWidth(1) painter.setPen(pen) painter.drawPath(path) path = QPainterPath() font.setPointSize(9) awkstr = ('%d' % card.current_awakening if card.current_awakening < card.max_awakening else '★') path.addText(rect.x(),rect.bottom(),font,awkstr) br = path.boundingRect() path.translate(rect.center().x()-br.center().x(), rect.center().y()-br.center().y()) pen.setBrush(QColor(0,0,0,0)) pen.setWidth(0) painter.setPen(pen) painter.setBrush(QBrush(Qt.yellow)) painter.drawPath(path) # Draw main attack damage #print(self.main_attack) if self.main_attack > 0: matkstr = '%d' % self.main_attack painter.setBrush(QBrush(COLORS[self.card.element[0]])) path = QPainterPath() font = QFont() font.setFamily('Helvetica') font.setWeight(QFont.Black) #font.setStretch(25) font.setPointSize(13) path.addText(rect.x(),rect.bottom(),font,matkstr) rect = QRectF(event.rect()) br = path.boundingRect() path.translate(rect.center().x()-br.center().x(), rect.center().y()-br.bottom()-1) # pen.setBrush(Qt.black) pen.setWidthF(.75) painter.setPen(pen) painter.drawPath(path) # Draw sub attack damage #print(self.main_attack) if self.sub_attack > 0: satkstr = '%d' % self.sub_attack painter.setBrush(QBrush(COLORS[self.card.element[1]])) path = QPainterPath() font = QFont() font.setFamily('Helvetica') font.setWeight(QFont.Black) #font.setStretch(25) font.setPointSize(12) path.addText(rect.x(),rect.bottom(),font,satkstr) rect = QRectF(event.rect()) br = path.boundingRect() path.translate(rect.center().x()-br.center().x(), rect.center().y()-br.top()+1) # pen.setBrush(Qt.black) pen.setWidthF(.75) painter.setPen(pen) painter.drawPath(path)
def drawGlyphPoints( painter, glyph, scale, rect, drawStartPoints=True, drawOnCurves=True, drawOffCurves=True, drawCoordinates=False, drawSelection=True, onCurveColor=None, otherColor=None, backgroundColor=None): if onCurveColor is None: layer = glyph.layer if layer is not None and layer.color is not None: onCurveColor = colorToQColor(layer.color) else: onCurveColor = defaultColor("glyphOnCurvePoints") if otherColor is None: otherColor = defaultColor("glyphOtherPoints") if backgroundColor is None: backgroundColor = defaultColor("background") # get the outline data outlineData = glyph.getRepresentation("defconQt.OutlineInformation") points = [] # start points if drawStartPoints and outlineData["startPoints"]: startWidth = startHeight = 15 * scale startHalf = startWidth / 2.0 path = QPainterPath() for point, angle in outlineData["startPoints"]: x, y = point if angle is not None: path.moveTo(x, y) path.arcTo(x - startHalf, y - startHalf, startWidth, startHeight, 180 - angle, 180) path.closeSubpath() else: path.addEllipse( x - startHalf, y - startHalf, startWidth, startHeight) startPointColor = QColor(otherColor) aF = startPointColor.alphaF() startPointColor.setAlphaF(aF * .3) painter.fillPath(path, startPointColor) # handles if drawOffCurves and outlineData["offCurvePoints"]: painter.save() painter.setPen(otherColor) for pt1, pt2 in outlineData["bezierHandles"]: x1, y1 = pt1 x2, y2 = pt2 # TODO: should lineWidth account scale by default drawLine(painter, x1, y1, x2, y2, 1.0 * scale) painter.restore() # on curve if drawOnCurves and outlineData["onCurvePoints"]: width = 7 * scale half = width / 2.0 smoothWidth = 8 * scale smoothHalf = smoothWidth / 2.0 painter.save() path = QPainterPath() selectedPath = QPainterPath() for point in outlineData["onCurvePoints"]: x, y = point["point"] points.append((x, y)) pointPath = QPainterPath() if point["smooth"]: x -= smoothHalf y -= smoothHalf pointPath.addEllipse(x, y, smoothWidth, smoothWidth) else: x -= half y -= half pointPath.addRect(x, y, width, width) if drawSelection and point["selected"]: selectedPath.addPath(pointPath) path.addPath(pointPath) pen = QPen(onCurveColor) pen.setWidthF(1.5 * scale) painter.setPen(pen) painter.fillPath(selectedPath, onCurveColor) painter.drawPath(path) painter.restore() # off curve if drawOffCurves and outlineData["offCurvePoints"]: # lines # points offWidth = 5 * scale offHalf = offWidth / 2.0 path = QPainterPath() selectedPath = QPainterPath() for point in outlineData["offCurvePoints"]: x, y = point["point"] points.append((x, y)) pointPath = QPainterPath() x -= offHalf y -= offHalf pointPath.addEllipse(x, y, offWidth, offWidth) if drawSelection and point["selected"]: selectedPath.addPath(pointPath) else: path.addPath(pointPath) pen = QPen(otherColor) pen.setWidthF(3.0 * scale) painter.save() painter.setPen(pen) painter.drawPath(path) painter.fillPath(path, QBrush(backgroundColor)) painter.drawPath(selectedPath) painter.fillPath(selectedPath, QBrush(otherColor)) painter.restore() # coordinates if drawCoordinates: otherColor = QColor(otherColor) otherColor.setAlphaF(otherColor.alphaF() * .6) painter.save() painter.setPen(otherColor) # TODO: decision + color font = painter.font() font.setPointSize(7) painter.setFont(font) for x, y in points: posX = x # TODO: We use + here because we align on top. Consider abstracting # yOffset. posY = y + 3 x = round(x, 1) if int(x) == x: x = int(x) y = round(y, 1) if int(y) == y: y = int(y) text = "%d %d" % (x, y) drawTextAtPoint(painter, text, posX, posY, scale, xAlign="center", yAlign="top") painter.restore()
def _drawGuidelines(painter, glyph, scale, rect, guidelines, drawLines=True, drawText=True, drawSelection=True, color=None): if not (drawLines or drawText): return xMin, yMin, width, height = rect xMax = xMin + width yMax = yMin + height fontSize = painter.font().pointSize() for line in guidelines: color_ = color if color_ is None: if line.color: color_ = colorToQColor(line.color) else: color_ = defaultColor("glyphGuideline") painter.save() painter.setPen(color) line1 = None if None not in (line.x, line.y): if line.angle is not None: # make an infinite line that intersects *(line.x, line.y)* # 1. make horizontal line from *(line.x, line.y)* of length # *diagonal* diagonal = math.sqrt(width**2 + height**2) line1 = QLineF(line.x, line.y, line.x + diagonal, line.y) # 2. set the angle # defcon guidelines are clockwise line1.setAngle(line.angle) # 3. reverse the line and set length to 2 * *diagonal* line1.setPoints(line1.p2(), line1.p1()) line1.setLength(2 * diagonal) else: line1 = QLineF(xMin, line.y, xMax, line.y) textX = 0 textY = 0 if drawLines: if line1 is not None: # line drawLine( painter, line1.x1(), line1.y1(), line1.x2(), line1.y2()) # point x, y = line.x, line.y smoothWidth = 8 * scale smoothHalf = smoothWidth / 2.0 painter.save() pointPath = QPainterPath() x -= smoothHalf y -= smoothHalf pointPath.addEllipse(x, y, smoothWidth, smoothWidth) pen = QPen(color_) pen.setWidthF(1 * scale) painter.setPen(pen) if drawSelection and line.selected: painter.fillPath(pointPath, color_) painter.drawPath(pointPath) painter.restore() else: if line.y is not None: drawLine(painter, xMin, line.y, xMax, line.y) elif line.x is not None: drawLine(painter, line.x, yMin, line.x, yMax) if drawText and line.name: if line1 is not None: textX = line.x textY = line.y - 6 * scale xAlign = "center" else: if line.y is not None: textX = glyph.width + 6 * scale textY = line.y - (fontSize / 3.5) * scale elif line.x is not None: textX = line.x + 6 * scale textY = 0 xAlign = "left" drawTextAtPoint( painter, line.name, textX, textY, scale, xAlign=xAlign) painter.restore()
if __name__ == '__main__': app = QApplication(sys.argv) w = QCustomPlot() regen = QCPBars(w.xAxis, w.yAxis) nuclear = QCPBars(w.xAxis, w.yAxis) fossil = QCPBars(w.xAxis, w.yAxis) w.addPlottable(regen) w.addPlottable(nuclear) w.addPlottable(fossil) pen = QPen() pen.setWidthF(1.2) fossil.setName('Fossil fuels') pen.setColor(QColor(255, 131, 0)) fossil.setPen(pen) fossil.setBrush(QColor(255, 131, 0, 50)) nuclear.setName('Nuclear') pen.setColor(QColor(1, 92, 192)) nuclear.setPen(pen) nuclear.setBrush(QColor(1, 92, 191, 50)) regen.setName('Regenerative') pen.setColor(QColor(150, 222, 0)) regen.setPen(pen) regen.setBrush(QColor(150, 222, 0, 70)) nuclear.moveAbove(fossil) regen.moveAbove(nuclear)
def drawGlyphPoints( painter, glyph, scale, drawStartPoints=True, drawOnCurves=True, drawOffCurves=True, drawCoordinates=False, drawBluesMarkers=True, onCurveColor=None, onCurveSmoothColor=None, offCurveColor=None, otherColor=None, backgroundColor=None): """ Draws a Glyph_ *glyph*’s points. .. _Glyph: http://ts-defcon.readthedocs.org/en/ufo3/objects/glyph.html """ if onCurveColor is None: onCurveColor = defaultColor("glyphOnCurvePoints") if onCurveSmoothColor is None: onCurveSmoothColor = defaultColor("glyphOnCurveSmoothPoints") if offCurveColor is None: offCurveColor = defaultColor("glyphOffCurvePoints") if otherColor is None: otherColor = defaultColor("glyphOtherPoints") if backgroundColor is None: backgroundColor = defaultColor("background") bluesMarkerColor = defaultColor("glyphBluesMarker") notchColor = defaultColor("glyphContourStroke").lighter(200) # get the outline data outlineData = glyph.getRepresentation("defconQt.OutlineInformation") points = [] # blue zones markers if drawBluesMarkers and drawOnCurves: font = glyph.font blues = [] if font.info.postscriptBlueValues: blues += font.info.postscriptBlueValues if font.info.postscriptOtherBlues: blues += font.info.postscriptOtherBlues if blues: blues_ = set(blues) size = 13 * scale snapSize = 17 * scale painter.save() pen = painter.pen() pen.setColor(QColor(255, 255, 255, 125)) pen.setWidth(0) painter.setPen(pen) for point in outlineData["onCurvePoints"]: x, y = point["point"] # TODO: we could add a non-overlapping interval tree special # cased for borders for yMin, yMax in zip(blues[::2], blues[1::2]): if not (y >= yMin and y <= yMax): continue # if yMin > 0 and y == yMin or yMin <= 0 and y == yMax: if y in blues_: path = lozengePath(x, y, snapSize) else: path = ellipsePath(x, y, size) painter.fillPath(path, bluesMarkerColor) painter.drawPath(path) painter.restore() # handles if drawOffCurves and outlineData["offCurvePoints"]: painter.save() painter.setPen(otherColor) for x1, y1, x2, y2 in outlineData["bezierHandles"]: drawLine(painter, x1, y1, x2, y2) painter.restore() # on curve if drawOnCurves and outlineData["onCurvePoints"]: size = 6.5 * scale smoothSize = 8 * scale startSize = 7 * scale loneStartSize = 12 * scale painter.save() notchPath = QPainterPath() path = QPainterPath() smoothPath = QPainterPath() for point in outlineData["onCurvePoints"]: x, y = point["point"] points.append((x, y)) # notch if "smoothAngle" in point: angle = point["smoothAngle"] t = Identity.rotate(angle) x1, y1 = t.transformPoint((-1.35 * scale, 0)) x2, y2 = -x1, -y1 notchPath.moveTo(x1 + x, y1 + y) notchPath.lineTo(x2 + x, y2 + y) # points if drawStartPoints and "startPointAngle" in point: angle = point["startPointAngle"] if angle is not None: pointPath = trianglePath(x, y, startSize, angle) else: pointPath = ellipsePath(x, y, loneStartSize) elif point["smooth"]: pointPath = ellipsePath(x, y, smoothSize) else: pointPath = rectanglePath(x, y, size) # store the path if point["smooth"]: smoothPath.addPath(pointPath) else: path.addPath(pointPath) # stroke pen = QPen(onCurveColor) pen.setWidthF(1.2 * scale) painter.setPen(pen) painter.drawPath(path) pen.setColor(onCurveSmoothColor) painter.setPen(pen) painter.drawPath(smoothPath) # notch pen.setColor(notchColor) pen.setWidth(0) painter.setPen(pen) painter.drawPath(notchPath) painter.restore() # off curve if drawOffCurves and outlineData["offCurvePoints"]: # points offSize = 4.25 * scale path = QPainterPath() for point in outlineData["offCurvePoints"]: x, y = point["point"] pointPath = ellipsePath(x, y, offSize) path.addPath(pointPath) pen = QPen(offCurveColor) pen.setWidthF(2.5 * scale) painter.save() painter.setPen(pen) painter.drawPath(path) painter.fillPath(path, QBrush(backgroundColor)) painter.restore() # coordinates if drawCoordinates: painter.save() painter.setPen(otherColor) font = painter.font() font.setPointSize(7) painter.setFont(font) for x, y in points: posX = x # TODO: We use + here because we align on top. Consider abstracting # yOffset. posY = y + 6 * scale x = round(x, 1) if int(x) == x: x = int(x) y = round(y, 1) if int(y) == y: y = int(y) text = "%d %d" % (x, y) drawTextAtPoint(painter, text, posX, posY, scale, xAlign="center", yAlign="top") painter.restore()
def drawMapObject(self, painter, object, color): painter.save() bounds = object.bounds() rect = QRectF(bounds) painter.translate(rect.topLeft()) rect.moveTopLeft(QPointF(0, 0)) cell = object.cell() if (not cell.isEmpty()): CellRenderer(painter).render(cell, QPointF(), object.size(), CellRenderer.BottomLeft) if (self.testFlag(RenderFlag.ShowTileObjectOutlines)): tile = cell.tile imgSize = tile.size() tileOffset = tile.offset() rect = QRectF(QPointF(tileOffset.x(), tileOffset.y() - imgSize.height()), QSizeF(imgSize)) pen = QPen(Qt.SolidLine) pen.setCosmetic(True) painter.setPen(pen) painter.drawRect(rect) pen.setStyle(Qt.DotLine) pen.setColor(color) painter.setPen(pen) painter.drawRect(rect) else: lineWidth = self.objectLineWidth() scale = self.painterScale() if lineWidth == 0: x = 1 else: x = lineWidth shadowDist = x / scale shadowOffset = QPointF(shadowDist * 0.5, shadowDist * 0.5) linePen = QPen(color, lineWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) #linePen.setCosmetic(True) shadowPen = QPen(linePen) shadowPen.setColor(Qt.black) brushColor = QColor(color) fillBrush = QBrush(brushColor) painter.setRenderHint(QPainter.Antialiasing) # Trying to draw an ellipse with 0-width is causing a hang in # CoreGraphics when drawing the path requested by the # QCoreGraphicsPaintEngine. Draw them as rectangle instead. shape = object.shape() if (shape == MapObject.Ellipse and ((rect.width() == 0.0) ^ (rect.height() == 0.0))): shape = MapObject.Rectangle x = shape if x==MapObject.Rectangle: if (rect.isNull()): rect = QRectF(QPointF(-10, -10), QSizeF(20, 20)) # Draw the shadow painter.setPen(shadowPen) painter.drawRect(rect.translated(shadowOffset)) painter.setPen(linePen) painter.setBrush(fillBrush) painter.drawRect(rect) elif x==MapObject.Polyline: screenPolygon = self.pixelToScreenCoords_(object.polygon()) thickShadowPen = QPen(shadowPen) thickLinePen = QPen(linePen) thickShadowPen.setWidthF(thickShadowPen.widthF() * 4) thickLinePen.setWidthF(thickLinePen.widthF() * 4) painter.setPen(shadowPen) painter.drawPolyline(screenPolygon.translated(shadowOffset)) painter.setPen(thickShadowPen) painter.drawPoint(screenPolygon.first() + shadowOffset) painter.setPen(linePen) painter.setBrush(fillBrush) painter.drawPolyline(screenPolygon) painter.setPen(thickLinePen) painter.drawPoint(screenPolygon.first()) elif x==MapObject.Polygon: screenPolygon = self.pixelToScreenCoords_(object.polygon()) thickShadowPen = QPen(shadowPen) thickLinePen = QPen(linePen) thickShadowPen.setWidthF(thickShadowPen.widthF() * 4) thickLinePen.setWidthF(thickLinePen.widthF() * 4) painter.setPen(shadowPen) painter.drawPolygon(screenPolygon.translated(shadowOffset)) painter.setPen(thickShadowPen) painter.drawPoint(screenPolygon.first() + shadowOffset) painter.setPen(linePen) painter.setBrush(fillBrush) painter.drawPolygon(screenPolygon) painter.setPen(thickLinePen) painter.drawPoint(screenPolygon.first()) elif x==MapObject.Ellipse: if (rect.isNull()): rect = QRectF(QPointF(-10, -10), QSizeF(20, 20)) # Draw the shadow painter.setPen(shadowPen) painter.drawEllipse(rect.translated(shadowOffset)) painter.setPen(linePen) painter.setBrush(fillBrush) painter.drawEllipse(rect) painter.restore()
def drawMapObject(self, painter, object, color): painter.save() pen = QPen(Qt.black) pen.setCosmetic(True) cell = object.cell() if (not cell.isEmpty()): tile = cell.tile imgSize = tile.size() pos = self.pixelToScreenCoords_(object.position()) tileOffset = tile.offset() CellRenderer(painter).render(cell, pos, object.size(), CellRenderer.BottomCenter) if (self.testFlag(RenderFlag.ShowTileObjectOutlines)): rect = QRectF(QPointF(pos.x() - imgSize.width() / 2 + tileOffset.x(), pos.y() - imgSize.height() + tileOffset.y()), QSizeF(imgSize)) pen.setStyle(Qt.SolidLine) painter.setPen(pen) painter.drawRect(rect) pen.setStyle(Qt.DotLine) pen.setColor(color) painter.setPen(pen) painter.drawRect(rect) else: lineWidth = self.objectLineWidth() scale = self.painterScale() x = 1 if lineWidth != 0: x = lineWidth shadowOffset = x / scale brushColor = QColor(color) brushColor.setAlpha(50) brush = QBrush(brushColor) pen.setJoinStyle(Qt.RoundJoin) pen.setCapStyle(Qt.RoundCap) pen.setWidth(lineWidth) colorPen = QPen(pen) colorPen.setColor(color) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) # TODO: Do something sensible to make null-sized objects usable x = object.shape() if x==MapObject.Ellipse: polygon = self.pixelRectToScreenPolygon(object.bounds()) tw = self.map().tileWidth() th = self.map().tileHeight() transformScale = QPointF(1, 1) if (tw > th): transformScale = QPointF(1, th/tw) else: transformScale = QPointF(tw/th, 1) l1 = polygon.at(1) - polygon.at(0) l2 = polygon.at(3) - polygon.at(0) trans = QTransform() trans.scale(transformScale.x(), transformScale.y()) trans.rotate(45) iTrans, ok = trans.inverted() l1x = iTrans.map(l1) l2x = iTrans.map(l2) ellipseSize = QSizeF(l1x.manhattanLength(), l2x.manhattanLength()) if (ellipseSize.width() > 0 and ellipseSize.height() > 0): painter.save() painter.setPen(pen) painter.translate(polygon.at(0)) painter.scale(transformScale.x(), transformScale.y()) painter.rotate(45) painter.drawEllipse(QRectF(QPointF(0, 0), ellipseSize)) painter.restore() painter.setBrush(Qt.NoBrush) painter.drawPolygon(polygon) painter.setPen(colorPen) painter.setBrush(Qt.NoBrush) painter.translate(QPointF(0, -shadowOffset)) painter.drawPolygon(polygon) painter.setBrush(brush) if (ellipseSize.width() > 0 and ellipseSize.height() > 0): painter.save() painter.translate(polygon.at(0)) painter.scale(transformScale.x(), transformScale.y()) painter.rotate(45) painter.drawEllipse(QRectF(QPointF(0, 0), ellipseSize)) painter.restore() elif x==MapObject.Rectangle: polygon = self.pixelRectToScreenPolygon(object.bounds()) painter.drawPolygon(polygon) painter.setPen(colorPen) painter.setBrush(brush) polygon.translate(0, -shadowOffset) painter.drawPolygon(polygon) elif x==MapObject.Polygon: pos = object.position() polygon = object.polygon().translated(pos) screenPolygon = self.pixelToScreenCoords_(polygon) thickPen = QPen(pen) thickColorPen = QPen(colorPen) thickPen.setWidthF(thickPen.widthF() * 4) thickColorPen.setWidthF(thickColorPen.widthF() * 4) painter.drawPolygon(screenPolygon) painter.setPen(thickPen) painter.drawPoint(screenPolygon.first()) painter.setPen(colorPen) painter.setBrush(brush) screenPolygon.translate(0, -shadowOffset) painter.drawPolygon(screenPolygon) painter.setPen(thickColorPen) painter.drawPoint(screenPolygon.first()) elif x==MapObject.Polyline: pos = object.position() polygon = object.polygon().translated(pos) screenPolygon = self.pixelToScreenCoords_(polygon) thickPen = QPen(pen) thickColorPen = QPen(colorPen) thickPen.setWidthF(thickPen.widthF() * 4) thickColorPen.setWidthF(thickColorPen.widthF() * 4) painter.drawPolyline(screenPolygon) painter.setPen(thickPen) painter.drawPoint(screenPolygon.first()) painter.setPen(colorPen) screenPolygon.translate(0, -shadowOffset) painter.drawPolyline(screenPolygon) painter.setPen(thickColorPen) painter.drawPoint(screenPolygon.first()) painter.restore()