def drawString(self, content, fontSize=256, color=QColor("red")): icon = self.icon() pixmap = icon.pixmap(512, 512) pixSize = pixmap.rect() painter = QPainter(pixmap) font = painter.font() font.setPixelSize(fontSize) painter.setFont(font) path = QPainterPath() path.addText(0, 0, font, content) pathBBox = path.boundingRect() xOffset = (pixSize.width() - pathBBox.width()) / 2 - pathBBox.left() yOffset = (pixSize.height() + pathBBox.height()) / 2 path.translate(xOffset, yOffset) ## paint shadow pathPen = QPen(QColor(0, 0, 0, 200)) pathPen.setWidth(180) painter.strokePath(path, pathPen) painter.fillPath(path, QBrush(color)) ## make number bolder pathPen = QPen(color) pathPen.setWidth(20) painter.strokePath(path, pathPen) painter.end() self.setIcon(QIcon(pixmap))
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25 * 10, 25 * 10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25 * 10 - 30) path = QPainterPath() path.addText(QPointF(50, 25 * 10 - 50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20, 20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = DelayedSpinBox(750) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def paintEvent(self, event): # Check whether this orb is enhanced if type(self.parent) == Board: enh = self.parent.enhanced[self.position] else: enh = False painter = QPainter(self) painter.drawPixmap(event.rect().adjusted(2,2,-2,-2), self.pixmap()) w = event.rect().width() if enh: path = QPainterPath() pen = QPen() pen.setWidth(1); pen.setBrush(Qt.white) brush = QBrush(Qt.yellow) font = QFont() font.setPointSize(20) font.setWeight(QFont.Black) path.addText(event.rect().x()+w-15,event.rect().y()+w-5,font,'+') painter.setPen(pen) painter.setBrush(brush) painter.setFont(font) painter.drawPath(path)
def draw_path(self): plan = self.plan rect = plan.mapRectToScene(plan.viewport().rect()) rect.setWidth(10**floor(log10(rect.width()/2))) text = "{} m".format(round(rect.width())) tran = self.deviceTransform(plan.viewportTransform()).inverted()[0] width = tran.mapRect(QRectF( plan.mapFromScene(rect.topLeft()), plan.mapFromScene(rect.bottomRight()))).width() view = tran.mapRect(plan.viewport().rect()) x0 = QPointF(view.right() - view.width()/15, view.bottom() - view.height()/15) x1 = x0 - QPointF(width, 0) head = QPointF(0, 8) path = QPainterPath() path.moveTo(x0) path.lineTo(x1) path.moveTo(x0 + head) path.lineTo(x0 - head) path.moveTo(x1 + head) path.lineTo(x1 - head) # add label font = QFont(plan.font()) font.setPointSize(14) rect = QFontMetrics(font).boundingRect(text) size = tran.mapRect(QRectF(rect)).size() w, h = size.width(), size.height() offs = [-w/2, -h/2] path.addText((x0+x1)/2 + QPointF(*offs), font, text) return path
def draw_path(self): plan = self.plan rect = plan.mapRectToScene(plan.viewport().rect()) rect.setWidth(10**floor(log10(rect.width() / 2))) text = "{} m".format(round(rect.width())) tran = self.deviceTransform(plan.viewportTransform()).inverted()[0] width = tran.mapRect( QRectF(plan.mapFromScene(rect.topLeft()), plan.mapFromScene(rect.bottomRight()))).width() view = tran.mapRect(plan.viewport().rect()) x0 = QPointF(view.right() - view.width() / 15, view.bottom() - view.height() / 15) x1 = x0 - QPointF(width, 0) head = QPointF(0, 8) path = QPainterPath() path.moveTo(x0) path.lineTo(x1) path.moveTo(x0 + head) path.lineTo(x0 - head) path.moveTo(x1 + head) path.lineTo(x1 - head) # add label font = QFont(plan.font()) font.setPointSize(14) rect = QFontMetrics(font).boundingRect(text) size = tran.mapRect(QRectF(rect)).size() w, h = size.width(), size.height() offs = [-w / 2, -h / 2] path.addText((x0 + x1) / 2 + QPointF(*offs), font, text) return path
def _drawTextShadow(painter: QPainter, x: int, y: int, text: str, font: QFont, text_color: QColor): # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path 1 outline_color = QColor(0, 0, 0, 64) outline_brush = QBrush(outline_color, Qt.SolidPattern) outline_pen = QPen(outline_brush, 8, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outline_pen) painter.setBrush(outline_brush) painter.drawPath(text_path) # draw outline path 2 outline_color = QColor(0, 0, 0, 128) outline_brush = QBrush(outline_color, Qt.SolidPattern) outline_pen = QPen(outline_brush, 4, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outline_pen) painter.setBrush(outline_brush) painter.drawPath(text_path) # draw text painter.setPen(text_color) painter.setFont(font) painter.drawText(x, y, text)
def paintEvent(self, e: QPaintEvent): super().paintEvent(e) painter = QtGui.QPainter(self) pen = QtGui.QPen() brush = QtGui.QBrush() brush.setStyle(Qt.SolidPattern) font = QtGui.QFont() font.setFamily('Montserrat') self.text_template_to_rect = {} for template_id, text in self.parent.render_options.items(): text_template = self.parent.meme_template[template_id] pen.setColor(QtGui.QColor(text_template.text_color)) painter.setPen(pen) keyframe = text_template.keyframes.interpolate( self.selected_frame_ind) font.setPixelSize(keyframe.text_size) painter.setFont(font) margin = 10 x, y, width, height = text_template.get_text_bounding_box( center_position=keyframe.position, font_size=keyframe.text_size, text=text) text_rect = QRect(x, y, width, height) self.text_template_to_rect[template_id] = text_rect background_rect = None if text_template.background_color is not None: background_rect = text_rect.adjusted(-margin, -margin, margin, margin) painter.fillRect(background_rect, QColor(text_template.background_color)) if template_id == self.parent.selected_text_template.id: rubber_rect = background_rect if background_rect is not None else text_rect self.rubberBand.setGeometry(rubber_rect) if text_template.stroke_width: painter.setRenderHint(QPainter.Antialiasing, True) brush.setColor(QColor(text_template.text_color)) painter.setBrush(brush) pen.setColor(QColor(text_template.stroke_color)) pen.setWidth(text_template.stroke_width * 2) painter.setPen(pen) path = QPainterPath() path.addText(text_rect.bottomLeft(), font, text) painter.strokePath(path, pen) painter.fillPath(path, brush) else: painter.drawText(text_rect, Qt.AlignHCenter | Qt.AlignVCenter, text) painter.end()
def _updateSequenceText(self): seq_item = self._seq_item is_on_top = self._is_on_top index = self._insertion.idx() base_text = self._seq_text font = styles.SEQUENCEFONT seq_font_h = styles.SEQUENCEFONTH insert_w = styles.INSERTWIDTH seq_font_char_w = styles.SEQUENCEFONTCHARWIDTH # draw sequence on the insert if base_text: # only draw sequences if they exist i.e. not None! len_BT = len(base_text) if is_on_top: angle_offset = 0 else: angle_offset = 180 if len_BT > 20: base_text = base_text[:17] + '...' len_BT = len(base_text) fraction_arc_len_per_char = ( 1.0 - 2.0 * _FRACTION_INSERT_TO_PAD) / (len_BT + 1) seq_item.setPen(QPen(Qt.NoPen)) seq_item.setBrush(QBrush(Qt.black)) seq_path = QPainterPath() loop_path = self.path() for i in range(len_BT): frac = _FRACTION_INSERT_TO_PAD + ( i + 1) * fraction_arc_len_per_char pt = loop_path.pointAtPercent(frac) tang_ang = loop_path.angleAtPercent(frac) temp_path = QPainterPath() # 1. draw the text temp_path.addText(0, 0, font, base_text[i if is_on_top else -i - 1]) # 2. center it at the zero point different for top and bottom # strands if not is_on_top: temp_path.translate(0, -seq_font_h - insert_w) temp_path.translate( QPointF(-seq_font_char_w / 2., -2 if is_on_top else seq_font_h)) mat = QTransform() # 3. rotate it mat.rotate(-tang_ang + angle_offset) rotated_path = mat.map(temp_path) # 4. translate the rotate object to it's position on the part rotated_path.translate(pt) seq_path.addPath(rotated_path) # end for seq_item.setPath(seq_path)
def plotSymbol(self): sym = QPainterPath() font = QFont('Sans Serif', 10, QFont.Black) sym.addText(0, 0, font, 'o') # Scale symbol to unit square box = sym.boundingRect() scale = 1. / max(box.width(), box.height()) tr = QTransform().scale(scale, scale) # Center symbol on (0, 0) tr.translate(-box.x() - box.width() / 2., -box.y() - box.height() / 2.) return tr.map(sym)
def plotSymbol(self): """Graphical representation of an optical vortex""" sym = QPainterPath() font = QFont('Sans Serif', 10, QFont.Black) sym.addText(0, 0, font, 'V') # scale symbol to unit square box = sym.boundingRect() scale = -1./max(box.width(), box.height()) tr = QTransform().scale(scale, scale) # center symbol on (0, 0) tr.translate(-box.x() - box.width()/2., -box.y() - box.height()/2.) return tr.map(sym)
def _updateSequenceText(self): seq_item = self._seq_item is_on_top = self._is_on_top index = self._insertion.idx() base_text = self._seq_text font = styles.SEQUENCEFONT seq_font_h = styles.SEQUENCEFONTH insert_w = styles.INSERTWIDTH seq_font_char_w = styles.SEQUENCEFONTCHARWIDTH # draw sequence on the insert if base_text: # only draw sequences if they exist i.e. not None! len_BT = len(base_text) if is_on_top: angle_offset = 0 else: angle_offset = 180 if len_BT > 20: base_text = base_text[:17] + '...' len_BT = len(base_text) fraction_arc_len_per_char = (1.0 - 2.0*_FRACTION_INSERT_TO_PAD) / (len_BT + 1) seq_item.setPen(QPen(Qt.NoPen)) seq_item.setBrush(QBrush(Qt.black)) seq_path = QPainterPath() loop_path = self.path() for i in range(len_BT): frac = _FRACTION_INSERT_TO_PAD + (i+1)*fraction_arc_len_per_char pt = loop_path.pointAtPercent(frac) tang_ang = loop_path.angleAtPercent(frac) temp_path = QPainterPath() # 1. draw the text temp_path.addText(0, 0, font, base_text[i if is_on_top else -i-1]) # 2. center it at the zero point different for top and bottom # strands if not is_on_top: temp_path.translate(0, -seq_font_h - insert_w) temp_path.translate(QPointF(-seq_font_char_w / 2., -2 if is_on_top else seq_font_h)) mat = QTransform() # 3. rotate it mat.rotate(-tang_ang + angle_offset) rotated_path = mat.map(temp_path) # 4. translate the rotate object to it's position on the part rotated_path.translate(pt) seq_path.addPath(rotated_path) # end for seq_item.setPath(seq_path)
def drawTextItem(self, pt, textitem): """Convert text to a path and draw it. """ path = QPainterPath() path.addText(pt, textitem.font(), textitem.text()) fill = self.emf.CreateSolidBrush(self.pencolor) self.emf.SelectObject(fill) self._createPath(path) self.emf.FillPath() self.emf.SelectObject(self.brush) self.emf.DeleteObject(fill)
def letterSymbol(self, letter): sym = QPainterPath() font = QFont() font.setStyleHint(QFont.SansSerif, QFont.PreferAntialias) font.setPointSize(12) sym.addText(0, 0, font, letter) # Scale symbol to unit square box = sym.boundingRect() scale = 1. / max(box.width(), box.height()) tr = QTransform().scale(scale, scale) # Center symbol on (0, 0) tr.translate(-box.x() - box.width() / 2., -box.y() - box.height() / 2.) return tr.map(sym)
def _updateSequenceText(self): seqItem = self._seqItem isOnTop = self._isOnTop index = self._insertion.idx() baseText = self._seqText font = styles.SEQUENCEFONT seqFontH = styles.SEQUENCEFONTH insertW = styles.INSERTWIDTH seqFontCharW = styles.SEQUENCEFONTCHARWIDTH # draw sequence on the insert if baseText: # only draw sequences if they exist i.e. not None! lenBT = len(baseText) if isOnTop: angleOffset = 0 else: angleOffset = 180 if lenBT > 20: baseText = baseText[:17] + '...' lenBT = len(baseText) fractionArclenPerChar = (1.0 - 2.0 * _fractionInsertToPad) / (lenBT + 1) seqItem.setPen(QPen(Qt.NoPen)) seqItem.setBrush(QBrush(Qt.black)) seqPath = QPainterPath() loopPath = self.path() for i in range(lenBT): frac = _fractionInsertToPad + (i + 1) * fractionArclenPerChar pt = loopPath.pointAtPercent(frac) tangAng = loopPath.angleAtPercent(frac) tempPath = QPainterPath() # 1. draw the text tempPath.addText(0, 0, font, baseText[i if isOnTop else -i - 1]) # 2. center it at the zero point different for top and bottom # strands if not isOnTop: tempPath.translate(0, -seqFontH - insertW) tempPath.translate( QPointF(-seqFontCharW / 2., -2 if isOnTop else seqFontH)) mat = QMatrix3x3() # 3. rotate it mat.rotate(-tangAng + angleOffset) rotatedPath = mat.map(tempPath) # 4. translate the rotate object to it's position on the part rotatedPath.translate(pt) seqPath.addPath(rotatedPath) # end for seqItem.setPath(seqPath)
def setupShapes(self): truck = QPainterPath() truck.setFillRule(Qt.WindingFill) truck.moveTo(0.0, 87.0) truck.lineTo(0.0, 60.0) truck.lineTo(10.0, 60.0) truck.lineTo(35.0, 35.0) truck.lineTo(100.0, 35.0) truck.lineTo(100.0, 87.0) truck.lineTo(0.0, 87.0) truck.moveTo(17.0, 60.0) truck.lineTo(55.0, 60.0) truck.lineTo(55.0, 40.0) truck.lineTo(37.0, 40.0) truck.lineTo(17.0, 60.0) truck.addEllipse(17.0, 75.0, 25.0, 25.0) truck.addEllipse(63.0, 75.0, 25.0, 25.0) clock = QPainterPath() clock.addEllipse(-50.0, -50.0, 100.0, 100.0) clock.addEllipse(-48.0, -48.0, 96.0, 96.0) clock.moveTo(0.0, 0.0) clock.lineTo(-2.0, -2.0) clock.lineTo(0.0, -42.0) clock.lineTo(2.0, -2.0) clock.lineTo(0.0, 0.0) clock.moveTo(0.0, 0.0) clock.lineTo(2.732, -0.732) clock.lineTo(24.495, 14.142) clock.lineTo(0.732, 2.732) clock.lineTo(0.0, 0.0) house = QPainterPath() house.moveTo(-45.0, -20.0) house.lineTo(0.0, -45.0) house.lineTo(45.0, -20.0) house.lineTo(45.0, 45.0) house.lineTo(-45.0, 45.0) house.lineTo(-45.0, -20.0) house.addRect(15.0, 5.0, 20.0, 35.0) house.addRect(-35.0, -15.0, 25.0, 25.0) text = QPainterPath() font = QFont() font.setPixelSize(50) fontBoundingRect = QFontMetrics(font).boundingRect("Qt") text.addText(-QPointF(fontBoundingRect.center()), font, "Qt") self.shapes = (clock, house, text, truck) self.shapeComboBox.activated.connect(self.shapeSelected)
def display_text(self, painter: QPainter, pen: QPen, x: int, y: int, string: str): if len(string) > 25: string = string[:25] string[-1] = "." string[-2] = "." string[-3] = "." white_pen = QPen(Qt.white) path = QPainterPath() white_pen.setWidth(3) painter.setPen(white_pen) font = QFont() font.setPointSize(SCALE(8)) painter.setFont(font) path.addText(SCALE(x - 1), SCALE(y), font, string) path.addText(SCALE(x - 1), SCALE(y - 1), font, string) path.addText(SCALE(x), SCALE(y - 1), font, string) path.addText(SCALE(x), SCALE(y), font, string) painter.drawPath(path) painter.setPen(pen) painter.drawText(SCALE(x), SCALE(y), string)
def _drawTextShadow(self, painter: QPainter, x: int, y: int, text: str): font = self.font() # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path 1 painter.setPen(self.outline_pen) painter.setBrush(self.outline_brush) painter.drawPath(text_path) # draw text painter.setPen(self.text_color) painter.setFont(font) # Note: The y-position is used as the baseline of the font. painter.drawText(x, y, text)
def _updateSequenceText(self): seqItem = self._seqItem isOnTop = self._isOnTop index = self._insertion.idx() baseText = self._seqText font = styles.SEQUENCEFONT seqFontH = styles.SEQUENCEFONTH insertW = styles.INSERTWIDTH seqFontCharW = styles.SEQUENCEFONTCHARWIDTH # draw sequence on the insert if baseText: # only draw sequences if they exist i.e. not None! lenBT = len(baseText) if isOnTop: angleOffset = 0 else: angleOffset = 180 if lenBT > 20: baseText = baseText[:17] + '...' lenBT = len(baseText) fractionArclenPerChar = (1.0-2.0*_fractionInsertToPad)/(lenBT+1) seqItem.setPen(QPen(Qt.NoPen)) seqItem.setBrush(QBrush(Qt.black)) seqPath = QPainterPath() loopPath = self.path() for i in range(lenBT): frac = _fractionInsertToPad + (i+1)*fractionArclenPerChar pt = loopPath.pointAtPercent(frac) tangAng = loopPath.angleAtPercent(frac) tempPath = QPainterPath() # 1. draw the text tempPath.addText(0,0, font, baseText[i if isOnTop else -i-1]) # 2. center it at the zero point different for top and bottom # strands if not isOnTop: tempPath.translate(0, -seqFontH - insertW) tempPath.translate(QPointF(-seqFontCharW/2., -2 if isOnTop else seqFontH)) mat = QMatrix3x3() # 3. rotate it mat.rotate(-tangAng + angleOffset) rotatedPath = mat.map(tempPath) # 4. translate the rotate object to it's position on the part rotatedPath.translate(pt) seqPath.addPath(rotatedPath) # end for seqItem.setPath(seqPath)
def _drawOutlinedText(painter: QPainter, x: int, y: int, text: str, font: QFont, textColor: QColor, outlineColor: QColor, outlineWidth: int=1): # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path outlineBrush = QBrush(outlineColor, Qt.SolidPattern) outlinePen = QPen(outlineBrush, outlineWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outlinePen) painter.setBrush(outlineBrush) painter.drawPath(text_path) # draw text painter.setPen(textColor) painter.setFont(font) painter.drawText(x, y, text)
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget): pen = QPen() pen.setWidth(1) painter.setRenderHint(QPainter.Antialiasing) pen.setColor(QColor(81, 81, 81, 255)) painter.setPen(pen) painter.setBrush(QBrush(QColor(81, 81, 81, 255), Qt.SolidPattern)) for i, score in enumerate(self.scores): path = QPainterPath() path.addText( -self.width, 14 + i * 16, QFont('monospace', 13, QFont.PreferNoHinting), f'{score.score:6}[{score.level:2}] {score.hero_name}') painter.drawPath(path)
def makePixmap(self, text): background = QPixmap(600, 80) background.fill(Qt.red) # Your background image painter = QPainter(background) textMask = QPainterPath() textMask.addRect(75, 20, 300, 40) # The white part textMask.addText(QPoint(90, 50), QFont("Helvetica [Cronyx]", 24), text) # the path will substract the text to the rect painter.setRenderHints(QPainter.Antialiasing | QPainter.TextAntialiasing) painter.fillPath(textMask, QBrush(Qt.white)) # Will draw the white part with the text "cut out" painter.end() return background
def text(text, font="Arial", font_size=6, line_width=1, color=QColor("blue"), matrix=np.eye(4, dtype='f4'), is_billboard=True, name="text", scale=0.1, origin=[0, 0, 0], u=[1, 0, 0], v=[0, 1, 0], w=[0, 0, 1]): ''' Warning, this function can crash if called before any call to QApplication(sys.argv) ''' color = ensure_QColor(color) origin = utils.to_numpy(origin) u = utils.to_numpy(u) v = utils.to_numpy(v) w = utils.to_numpy(w) indices = [] vertices = [] path = QPainterPath() path.addText(QPointF(0, 0), QFont(font, font_size), text) polygons = path.toSubpathPolygons() for polygon in polygons: for point in polygon: indices.append(len(vertices)) p = utils.to_numpy([point.x(), point.y(), 0]) * scale vertices.append(origin + p[0] * u + p[1] * v + p[2] * w) indices.append(-1) return Actors.Actor(geometry=Geometry.Geometry( indices=Array.Array(ndarray=np.array(indices, 'u4')), attribs=Geometry.Attribs(vertices=Array.Array( ndarray=np.array(vertices, 'f4'))), primitive_type=Geometry.PrimitiveType.LINE_LOOP), effect=CustomEffects.emissive( color, line_width=line_width, is_billboard=is_billboard), transform=ensure_Transform(matrix), name=f"{name}_{text}")
def createAxisLabelPixmap(self): pixmap = QPixmap(250, 250) pixmap.fill(self.backgroundColor) painter = QPainter() painter.begin(pixmap) font = QFont() font.setBold(True) font.setPixelSize(250 - 30) path = QPainterPath() path.addText(QPointF(50, 250 - 50), font, self.axis) brush = QBrush(self.foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(self.labelsWidth, self.labelsheight), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def draw_text_n_outline(self, painter: QPainter, x, y, outline_width, outline_blur, text): outline_color = QColor(config.outline_color) font = self.font() text_path = QPainterPath() if config.R2L_from_B: text_path.addText(x, y, font, ' ' + r2l(text.strip()) + ' ') else: text_path.addText(x, y, font, text) # draw blur range_width = range(outline_width, outline_width + outline_blur) # ~range_width = range(outline_width + outline_blur, outline_width, -1) for width in range_width: if width == min(range_width): alpha = 200 else: alpha = (max(range_width) - width) / max(range_width) * 200 alpha = int(alpha) blur_color = QColor(outline_color.red(), outline_color.green(), outline_color.blue(), alpha) blur_brush = QBrush(blur_color, Qt.SolidPattern) blur_pen = QPen(blur_brush, width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(blur_pen) painter.drawPath(text_path) # draw outline outline_color = QColor(outline_color.red(), outline_color.green(), outline_color.blue(), 255) outline_brush = QBrush(outline_color, Qt.SolidPattern) outline_pen = QPen(outline_brush, outline_width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outline_pen) painter.drawPath(text_path) # draw text color = self.palette().color(QPalette.Text) painter.setPen(color) painter.drawText(x, y, text)
def paint( self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget): pen = QPen() pen.setWidth(1) painter.setRenderHint(QPainter.Antialiasing) pen.setColor(QColor(81, 81, 81, 255)) painter.setPen(pen) painter.setBrush(QBrush(QColor(81, 81, 81, 255), Qt.SolidPattern)) path = QPainterPath() path.addText( -self.width, self.height, QFont('monospace', 13, QFont.PreferNoHinting), self.text) painter.drawPath(path)
def draw_abuse(self, note: ChartPicNote, group): if note.delta == 0: return x_note = self.get_x(note.lane + note.span / 2, group) - note.note_pic_smol.width() // 2 y_early = self.get_y(note.sec + note.early / 1000, group) shifted_y_early = y_early - note.note_pic_smol.height() // 2 y_late = self.get_y(note.sec + note.late / 1000, group) shifted_y_late = y_late - note.note_pic_smol.height() // 2 self.p.drawImage(QPoint(x_note, shifted_y_early), note.note_pic_smol) self.p.drawImage(QPoint(x_note, shifted_y_late), note.note_pic_smol) lane_l = self.get_x(0, group) lane_r = self.get_x(self.lane_count - 1, group) self.p.setPen(QPen(Qt.green)) self.p.drawLine(lane_l, y_early, lane_r, y_early) self.p.setPen(QPen(Qt.red)) self.p.drawLine(lane_l, y_late, lane_r, y_late) x = self.get_x(note.lane + note.span / 2, group) - note.note_pic.width() // 2 y = self.get_y(note.sec, group) + note.note_pic.height() font = QFont() font.setBold(True) font.setPixelSize(30) pen = QPen() pen.setWidth(1) pen.setColor(Qt.white) if note.great: brush = QBrush(QColor(66, 13, 110)) else: brush = QBrush(Qt.black) path = QPainterPath() path.addText(x, y, font, str(note.delta)) self.p.setFont(font) self.p.setPen(pen) self.p.setBrush(brush) self.p.drawPath(path) font.setPixelSize(24) path = QPainterPath() path.addText(x, y + 40, font, "{} {}".format(note.early, note.late)) self.p.drawPath(path)
def paint(self, p, *args): super(RubberBand, self).paint(p) # p.drawRect(self.boundingRect()) if not roam.config.settings.get("draw_distance", True): return offset = QPointF(5, 5) nodescount = self.numberOfVertices() for index in range(nodescount, -1, -1): if index == 0: return qgspoint = self.getPoint(0, index) qgspointbefore = self.getPoint(0, index - 1) # No point before means we are the first index and there is nothing # before us. if not qgspointbefore: return if qgspoint and qgspointbefore: distance = self.distancearea.measureLine( qgspoint, qgspointbefore) if int(distance) == 0: continue text = QgsDistanceArea.formatDistance(distance, 3, self.unit, keepBaseUnit=False) linegeom = QgsGeometry.fromPolyline( [QgsPoint(qgspoint), QgsPoint(qgspointbefore)]) midpoint = linegeom.centroid().asPoint() midpoint = self.toCanvasCoordinates(midpoint) - self.pos() midpoint += offset path = QPainterPath() path.addText(midpoint, self.font, text) p.setPen(self.blackpen) p.setRenderHints(QPainter.Antialiasing) p.setFont(self.font) p.setBrush(self.whitebrush) p.drawPath(path)
def paint(self, painter, style, widget=None): assert isinstance(painter, QPainter) if self.isSelected(): brush = QBrush(Qt.yellow) else: brush = QBrush(Qt.white) pen = QPen(Qt.black) circle_path = QPainterPath() circle_path.addEllipse(self.boundingRect()) painter.fillPath(circle_path, brush) painter.strokePath(circle_path, pen) text_path = QPainterPath() text_path.addText(0, 0, QFont(), str(self.node)) box = text_path.boundingRect() text_path.translate(-box.center()) painter.fillPath(text_path, QBrush(Qt.black))
def paintEvent(self, QPaintEvent): painter = QPainter(self) painter.save() metrics = QFontMetrics(self.getQFont()) path = QPainterPath() pen = QPen(QColor(0, 0, 0, 230)) painter.setRenderHint(QPainter.Antialiasing) penwidth = 4 pen.setWidth(penwidth) len = metrics.width(self.__Dtext) w = self.width() px = (len - w) / 2 if px < 0: px = -px py = (self.height() - metrics.height()) / 2 + metrics.ascent() if py < 0: py = -py path.addText(px + 2, py + 2, self.getQFont(), self.__Dtext) painter.strokePath(path, pen) painter.drawPath(path) painter.fillPath(path, QBrush(self.getQColor())) painter.restore()
def _drawOutlinedText(painter: QPainter, x: int, y: int, text: str, font: QFont, textColor: QColor, outlineColor: QColor, outlineWidth: int = 1): # setup outline path text_path = QPainterPath() text_path.addText(x, y, font, text) # draw outline path outlineBrush = QBrush(outlineColor, Qt.SolidPattern) outlinePen = QPen(outlineBrush, outlineWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) painter.setPen(outlinePen) painter.setBrush(outlineBrush) painter.drawPath(text_path) # draw text painter.setPen(textColor) painter.setFont(font) painter.drawText(x, y, text)
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25*10, 25*10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25*10-30) path = QPainterPath() path.addText(QPointF(50, 25*10-50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20,20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = DelayedSpinBox(750) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor("#888888"))) path1 = QPainterPath() path1.moveTo(5, 5) path1.cubicTo(40, 5, 50, 50, 99, 99) path1.cubicTo(5, 99, 50, 50, 5, 5) painter.drawPath(path1) painter.drawPie(130, 20, 90, 60, 30 * 16, 120 * 16) painter.drawChord(240, 30, 90, 60, 0, 16 * 180) painter.drawRoundedRect(20, 120, 80, 50, 10, 10) polygon = QPolygon() polygon.append(QPoint(130, 140)) polygon.append(QPoint(180, 170)) polygon.append(QPoint(180, 140)) polygon.append(QPoint(220, 110)) polygon.append(QPoint(140, 100)) painter.drawPolygon(polygon) painter.drawRect(250, 110, 60, 60) baseline = QPointF(20, 250) font = QFont("Georgia", 55) path2 = QPainterPath() path2.addText(baseline, font, "Q") painter.drawPath(path2) painter.drawEllipse(140, 200, 60, 60) painter.drawEllipse(240, 200, 90, 60)
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget: QWidget): pen = QPen() pen.setWidth(3) painter.setRenderHint(QPainter.Antialiasing) pen.setColor(QColor(61, 61, 61, 255)) painter.setPen(pen) painter.setBrush(QBrush(QColor(61, 61, 61, 255), Qt.SolidPattern)) painter.drawRect(QRectF(-self.maxWidth / 2, -10, self.maxWidth, 20)) painter.setBrush(QBrush(QColor(240, 217, 108, 255), Qt.SolidPattern)) painter.drawRect(QRectF(-self.maxWidth / 2, -10, self.displayWidth, 20)) path = QPainterPath() path.addText( -self.maxWidth / 2, 35, QFont('monospace', 18, QFont.Bold), f'{self.name} Lv.{self.level} Exp. {self.actualExperience:{len(str(self.maxExperience))}}/{self.maxExperience}' ) # pen.setColor(Qt.white) pen.setWidth(2) painter.setPen(pen) painter.setBrush(QBrush(QColor(0, 0, 0, 61), Qt.SolidPattern)) painter.drawPath(path)
def createHoneycombGrid(self, part_item, radius, bounds): """Instantiate an area of griditems arranged on a honeycomb lattice. Args: part_item (TYPE): Description radius (TYPE): Description bounds (TYPE): Description Returns: TYPE: Description """ doLattice = HoneycombDnaPart.latticeCoordToPositionXY doPosition = HoneycombDnaPart.positionToLatticeCoordRound isEven = HoneycombDnaPart.isEvenParity x_l, x_h, y_l, y_h = bounds x_l = x_l + HoneycombDnaPart.PAD_GRID_XL x_h = x_h + HoneycombDnaPart.PAD_GRID_XH y_h = y_h + HoneycombDnaPart.PAD_GRID_YL y_l = y_l + HoneycombDnaPart.PAD_GRID_YH dot_size, half_dot_size = self.dots sf = part_item.scale_factor points = self.points row_l, col_l = doPosition(radius, x_l, -y_l, False, False, scale_factor=sf) row_h, col_h = doPosition(radius, x_h, -y_h, True, True, scale_factor=sf) redo_neighbors = (row_l, col_l, row_h, col_h) != self.previous_grid_bounds or\ self.previous_grid_type != self.grid_type self.previous_grid_type = self.grid_type path = QPainterPath() is_pen_down = False draw_lines = self.draw_lines if redo_neighbors: point_coordinates = dict() neighbor_map = dict() self.points_dict = dict() for row in range(row_l, row_h): for column in range(col_l, col_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if draw_lines: if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) """ +x is Left and +y is down origin of ellipse is Top Left corner so we subtract half in X and subtract in y """ pt = GridPoint(x - half_dot_size, -y - half_dot_size, dot_size, self, coord=(row, column)) if self._draw_gridpoint_coordinates: font = QFont(styles.THE_FONT) path.addText(x - 10, -y + 5, font, "%s,%s" % (-row, column)) pt.setPen( getPenObj(styles.GRAY_STROKE, styles.EMPTY_HELIX_STROKE_WIDTH)) # if x == 0 and y == 0: # pt.setBrush(getBrushObj(Qt.gray)) points.append(pt) self.points_dict[(-row, column)] = pt if redo_neighbors: point_coordinates[(-row, column)] = (x, -y) # This is reversed since the Y is mirrored if not HoneycombDnaPart.isEvenParity(row, column): neighbor_map[(-row, column)] = [(-row - 1, column), (-row, column + 1), (-row, column - 1)] else: neighbor_map[(-row, column)] = [(-row + 1, column), (-row, column - 1), (-row, column + 1)] self.previous_grid_bounds = (row_l, col_l, row_h, col_h) is_pen_down = False if draw_lines: for column in range(col_l, col_h + 1): for row in range(row_l, row_h): x, y = doLattice(radius, row, column, scale_factor=sf) if is_pen_down and isEven(row, column): path.lineTo(x, -y) is_pen_down = False else: is_pen_down = True path.moveTo(x, -y) is_pen_down = False # end for j self._path.setPath(path) if redo_neighbors: self.part_item.setNeighborMap(neighbor_map=neighbor_map) self.part_item.setPointMap(point_map=point_coordinates)
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 createSquareGrid(self, part_item, radius, bounds): """Instantiate an area of griditems arranged on a square lattice. Args: part_item (TYPE): Description radius (TYPE): Description bounds (TYPE): Description Returns: TYPE: Description """ doLattice = SquareDnaPart.latticeCoordToModelXY doPosition = SquareDnaPart.positionToLatticeCoordRound x_l, x_h, y_l, y_h = bounds x_l = x_l + SquareDnaPart.PAD_GRID_XL x_h = x_h + SquareDnaPart.PAD_GRID_XH y_h = y_h + SquareDnaPart.PAD_GRID_YL y_l = y_l + SquareDnaPart.PAD_GRID_YH dot_size, half_dot_size = self.dots sf = part_item.scale_factor points = self.points row_l, col_l = doPosition(radius, x_l, -y_l, scale_factor=sf) row_h, col_h = doPosition(radius, x_h, -y_h, scale_factor=sf) redo_neighbors = (row_l, col_l, row_h, col_h) != \ self.previous_grid_bounds or self.previous_grid_type != self.grid_type self.previous_grid_type = self.grid_type if redo_neighbors: neighbor_map = dict() path = QPainterPath() is_pen_down = False draw_lines = self.draw_lines for row in range(row_l, row_h + 1): for column in range(col_l, col_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if draw_lines: if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) """ +x is Left and +y is down origin of ellipse is Top Left corner so we subtract half in X and subtract in y """ pt = GridPoint(x - half_dot_size, -y - half_dot_size, dot_size, self, coord=(row, column)) if self._draw_gridpoint_coordinates: font = QFont(styles.THE_FONT) path.addText(x - 10, -y + 5, font, "%s,%s" % (-row, column)) pt.setPen(getPenObj(styles.GRAY_STROKE, styles.EMPTY_HELIX_STROKE_WIDTH)) # if x == 0 and y == 0: # pt.setBrush(getBrushObj(Qt.gray)) points.append(pt) self.points_dict[(-row, column)] = pt if redo_neighbors: self.previous_grid_bounds = (row_l, col_l, row_h, col_h) is_pen_down = False # pen up # DO VERTICAL LINES if draw_lines: for column in range(col_l, col_h + 1): for row in range(row_l, row_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) is_pen_down = False # pen up self._path.setPath(path)
def createSquareGrid(self, part_item: SliceNucleicAcidPartItemT, radius: float, bounds: RectT): """Instantiate an area of griditems arranged on a square lattice. Args: part_item: Description radius: Description bounds: Description """ doLattice = SquareDnaPart.latticeCoordToModelXY doPosition = SquareDnaPart.positionToLatticeCoordRound x_l, x_h, y_l, y_h = bounds x_l = x_l + SquareDnaPart.PAD_GRID_XL x_h = x_h + SquareDnaPart.PAD_GRID_XH y_h = y_h + SquareDnaPart.PAD_GRID_YL y_l = y_l + SquareDnaPart.PAD_GRID_YH dot_size, half_dot_size = self.dots sf = part_item.scale_factor points = self.points row_l, col_l = doPosition(radius, x_l, -y_l, scale_factor=sf) row_h, col_h = doPosition(radius, x_h, -y_h, scale_factor=sf) redo_neighbors = (row_l, col_l, row_h, col_h) != \ self.previous_grid_bounds or self.previous_grid_type != self.grid_type self.previous_grid_type = self.grid_type if redo_neighbors: neighbor_map = dict() path = QPainterPath() is_pen_down = False draw_lines = self.draw_lines for row in range(row_l, row_h + 1): for column in range(col_l, col_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if draw_lines: if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) """ +x is Left and +y is down origin of ellipse is Top Left corner so we subtract half in X and subtract in y """ pt = GridPoint(x - half_dot_size, -y - half_dot_size, dot_size, self, coord=(row, column)) if self._draw_gridpoint_coordinates: font = QFont(styles.THE_FONT) path.addText(x - 10, -y + 5, font, "%s,%s" % (-row, column)) pt.setPen(getPenObj(styles.GRAY_STROKE, styles.EMPTY_HELIX_STROKE_WIDTH)) # if x == 0 and y == 0: # pt.setBrush(getBrushObj(Qt.gray)) points.append(pt) self.points_dict[(-row, column)] = pt if redo_neighbors: self.previous_grid_bounds = (row_l, col_l, row_h, col_h) is_pen_down = False # pen up # DO VERTICAL LINES if draw_lines: for column in range(col_l, col_h + 1): for row in range(row_l, row_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) is_pen_down = False # pen up self._path.setPath(path)
def createHoneycombGrid(self, part_item: SliceNucleicAcidPartItemT, radius: float, bounds: RectT): """Instantiate an area of griditems arranged on a honeycomb lattice. Args: part_item: Description radius: Description bounds: Description """ doLattice = HoneycombDnaPart.latticeCoordToModelXY doPosition = HoneycombDnaPart.positionModelToLatticeCoord isEven = HoneycombDnaPart.isEvenParity x_l, x_h, y_l, y_h = bounds x_l = x_l + HoneycombDnaPart.PAD_GRID_XL x_h = x_h + HoneycombDnaPart.PAD_GRID_XH y_h = y_h + HoneycombDnaPart.PAD_GRID_YL y_l = y_l + HoneycombDnaPart.PAD_GRID_YH dot_size, half_dot_size = self.dots sf = part_item.scale_factor points = self.points row_l, col_l = doPosition(radius, x_l, -y_l, scale_factor=sf) row_h, col_h = doPosition(radius, x_h, -y_h, scale_factor=sf) redo_neighbors = (row_l, col_l, row_h, col_h) != self.previous_grid_bounds or\ self.previous_grid_type != self.grid_type self.previous_grid_type = self.grid_type path = QPainterPath() is_pen_down = False draw_lines = self.draw_lines if redo_neighbors: self.points_dict = dict() for row in range(row_l, row_h): for column in range(col_l, col_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if draw_lines: if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) """ +x is Left and +y is down origin of ellipse is Top Left corner so we subtract half in X and subtract in y """ pt = GridPoint(x - half_dot_size, -y - half_dot_size, dot_size, self, coord=(row, column)) if self._draw_gridpoint_coordinates: font = QFont(styles.THE_FONT, 6) path.addText(x - 5, -y + 4, font, "%s,%s" % (-row, column)) pt.setPen( getPenObj(styles.GRAY_STROKE, styles.EMPTY_HELIX_STROKE_WIDTH)) # if x == 0 and y == 0: # pt.setBrush(getBrushObj(Qt.gray)) points.append(pt) self.points_dict[(-row, column)] = pt if redo_neighbors: self.previous_grid_bounds = (row_l, col_l, row_h, col_h) is_pen_down = False if draw_lines: for column in range(col_l, col_h + 1): for row in range(row_l, row_h): x, y = doLattice(radius, row, column, scale_factor=sf) if is_pen_down and isEven(row, column): path.lineTo(x, -y) is_pen_down = False else: is_pen_down = True path.moveTo(x, -y) is_pen_down = False # end for j self._path.setPath(path)
def __init__(self): super(Window, self).__init__() rectPath = QPainterPath() rectPath.moveTo(20.0, 30.0) rectPath.lineTo(80.0, 30.0) rectPath.lineTo(80.0, 70.0) rectPath.lineTo(20.0, 70.0) rectPath.closeSubpath() roundRectPath = QPainterPath() roundRectPath.moveTo(80.0, 35.0) roundRectPath.arcTo(70.0, 30.0, 10.0, 10.0, 0.0, 90.0) roundRectPath.lineTo(25.0, 30.0) roundRectPath.arcTo(20.0, 30.0, 10.0, 10.0, 90.0, 90.0) roundRectPath.lineTo(20.0, 65.0) roundRectPath.arcTo(20.0, 60.0, 10.0, 10.0, 180.0, 90.0) roundRectPath.lineTo(75.0, 70.0) roundRectPath.arcTo(70.0, 60.0, 10.0, 10.0, 270.0, 90.0) roundRectPath.closeSubpath() ellipsePath = QPainterPath() ellipsePath.moveTo(80.0, 50.0) ellipsePath.arcTo(20.0, 30.0, 60.0, 40.0, 0.0, 360.0) piePath = QPainterPath() piePath.moveTo(50.0, 50.0) piePath.lineTo(65.0, 32.6795) piePath.arcTo(20.0, 30.0, 60.0, 40.0, 60.0, 240.0) piePath.closeSubpath() polygonPath = QPainterPath() polygonPath.moveTo(10.0, 80.0) polygonPath.lineTo(20.0, 10.0) polygonPath.lineTo(80.0, 30.0) polygonPath.lineTo(90.0, 70.0) polygonPath.closeSubpath() groupPath = QPainterPath() groupPath.moveTo(60.0, 40.0) groupPath.arcTo(20.0, 20.0, 40.0, 40.0, 0.0, 360.0) groupPath.moveTo(40.0, 40.0) groupPath.lineTo(40.0, 80.0) groupPath.lineTo(80.0, 80.0) groupPath.lineTo(80.0, 40.0) groupPath.closeSubpath() textPath = QPainterPath() timesFont = QFont('Times', 50) timesFont.setStyleStrategy(QFont.ForceOutline) textPath.addText(10, 70, timesFont, "Qt") bezierPath = QPainterPath() bezierPath.moveTo(20, 30) bezierPath.cubicTo(80, 0, 50, 50, 80, 80) starPath = QPainterPath() starPath.moveTo(90, 50) for i in range(1, 5): starPath.lineTo(50 + 40 * cos(0.8 * i * pi), 50 + 40 * sin(0.8 * i * pi)) starPath.closeSubpath() self.renderAreas = [RenderArea(rectPath), RenderArea(roundRectPath), RenderArea(ellipsePath), RenderArea(piePath), RenderArea(polygonPath), RenderArea(groupPath), RenderArea(textPath), RenderArea(bezierPath), RenderArea(starPath)] assert len(self.renderAreas) == 9 self.fillRuleComboBox = QComboBox() self.fillRuleComboBox.addItem("Odd Even", Qt.OddEvenFill) self.fillRuleComboBox.addItem("Winding", Qt.WindingFill) fillRuleLabel = QLabel("Fill &Rule:") fillRuleLabel.setBuddy(self.fillRuleComboBox) self.fillColor1ComboBox = QComboBox() self.populateWithColors(self.fillColor1ComboBox) self.fillColor1ComboBox.setCurrentIndex( self.fillColor1ComboBox.findText("mediumslateblue")) self.fillColor2ComboBox = QComboBox() self.populateWithColors(self.fillColor2ComboBox) self.fillColor2ComboBox.setCurrentIndex( self.fillColor2ComboBox.findText("cornsilk")) fillGradientLabel = QLabel("&Fill Gradient:") fillGradientLabel.setBuddy(self.fillColor1ComboBox) fillToLabel = QLabel("to") fillToLabel.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.penWidthSpinBox = QSpinBox() self.penWidthSpinBox.setRange(0, 20) penWidthLabel = QLabel("&Pen Width:") penWidthLabel.setBuddy(self.penWidthSpinBox) self.penColorComboBox = QComboBox() self.populateWithColors(self.penColorComboBox) self.penColorComboBox.setCurrentIndex( self.penColorComboBox.findText('darkslateblue')) penColorLabel = QLabel("Pen &Color:") penColorLabel.setBuddy(self.penColorComboBox) self.rotationAngleSpinBox = QSpinBox() self.rotationAngleSpinBox.setRange(0, 359) self.rotationAngleSpinBox.setWrapping(True) self.rotationAngleSpinBox.setSuffix(u'\N{DEGREE SIGN}') rotationAngleLabel = QLabel("&Rotation Angle:") rotationAngleLabel.setBuddy(self.rotationAngleSpinBox) self.fillRuleComboBox.activated.connect(self.fillRuleChanged) self.fillColor1ComboBox.activated.connect(self.fillGradientChanged) self.fillColor2ComboBox.activated.connect(self.fillGradientChanged) self.penColorComboBox.activated.connect(self.penColorChanged) for i in range(Window.NumRenderAreas): self.penWidthSpinBox.valueChanged.connect(self.renderAreas[i].setPenWidth) self.rotationAngleSpinBox.valueChanged.connect(self.renderAreas[i].setRotationAngle) topLayout = QGridLayout() for i in range(Window.NumRenderAreas): topLayout.addWidget(self.renderAreas[i], i / 3, i % 3) mainLayout = QGridLayout() mainLayout.addLayout(topLayout, 0, 0, 1, 4) mainLayout.addWidget(fillRuleLabel, 1, 0) mainLayout.addWidget(self.fillRuleComboBox, 1, 1, 1, 3) mainLayout.addWidget(fillGradientLabel, 2, 0) mainLayout.addWidget(self.fillColor1ComboBox, 2, 1) mainLayout.addWidget(fillToLabel, 2, 2) mainLayout.addWidget(self.fillColor2ComboBox, 2, 3) mainLayout.addWidget(penWidthLabel, 3, 0) mainLayout.addWidget(self.penWidthSpinBox, 3, 1, 1, 3) mainLayout.addWidget(penColorLabel, 4, 0) mainLayout.addWidget(self.penColorComboBox, 4, 1, 1, 3) mainLayout.addWidget(rotationAngleLabel, 5, 0) mainLayout.addWidget(self.rotationAngleSpinBox, 5, 1, 1, 3) self.setLayout(mainLayout) self.fillRuleChanged() self.fillGradientChanged() self.penColorChanged() self.penWidthSpinBox.setValue(2) self.setWindowTitle("Painter Paths")
class RouteText(QGraphicsItem): def __init__(self, text='S', startp=Point(x=0.0, y=0.0),): """ Initialisation of the class. """ QGraphicsItem.__init__(self) self.setFlag(QGraphicsItem.ItemIsSelectable, False) self.text = text self.sc = 1.0 self.startp = QtCore.QPointF(startp.x, -startp.y) pencolor = QColor(0, 200, 255) self.brush = QColor(0, 100, 255) self.pen = QPen(pencolor, 1, QtCore.Qt.SolidLine) self.pen.setCosmetic(True) self.path = QPainterPath() self.path.addText(QtCore.QPointF(0, 0), QFont("Arial", 10/self.sc), self.text) def contains_point(self, point): """ Text cannot be selected. Return maximal distance """ return float(0x7fffffff) def setSelected(self, *args): """ Override inherited function - with possibility to be called with multiple arguments """ def paint(self, painter, option, widget=None): """ Method for painting the arrow. """ demat = painter.deviceTransform() self.sc = demat.m11() # painter.setClipRect(self.boundingRect()) painter.setPen(self.pen) painter.setBrush(self.brush) painter.scale(1/self.sc, 1/self.sc) painter.translate(self.startp.x() * self.sc, self.startp.y() * self.sc) painter.drawPath(self.path) def shape(self): """ Reimplemented function to select outline only. @return: Returns the Outline only """ logger.debug("Hier sollte ich nicht sein") return super(RouteText, self).shape() def boundingRect(self): """ Required method for painting. Inherited by Painterpath @return: Gives the Bounding Box """ rect = self.path.boundingRect().getRect() newrect = QtCore.QRectF(self.startp.x()+rect[0]/self.sc, self.startp.y()+rect[1]/self.sc, rect[2]/self.sc, rect[3]/self.sc) return newrect