def _drawIcon(self, color=Qt.black): self.setForeground(QBrush(color)) if self.isRootNode: pixmap = QPixmap(20, 20) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) pen = QPen(color) pen.setWidth(1) painter.setPen(pen) painter.setBrush(color) painter.setRenderHint(QPainter.Antialiasing) if not self.isExpanded: arrowRightPolygon = [ QPoint(6, 6), QPoint(6, 14), QPoint(14, 10) ] painter.drawPolygon(QPolygon(arrowRightPolygon)) else: arrowDownPolygon = [ QPoint(6, 6), QPoint(15, 6), QPoint(10, 14) ] painter.drawPolygon(QPolygon(arrowDownPolygon)) painter.end() self.setIcon(QIcon(pixmap))
def draw_filled_polygon(self, outline_pen_with=0): if not self.scale_polygon_colors == None: painter_filled_polygon = QPainter(self) painter_filled_polygon.setRenderHint(QPainter.Antialiasing) # Koordinatenursprung in die Mitte der Flaeche legen painter_filled_polygon.translate(self.width() / 2, self.height() / 2) painter_filled_polygon.setPen(Qt.NoPen) self.pen.setWidth(outline_pen_with) if outline_pen_with > 0: painter_filled_polygon.setPen(self.pen) colored_scale_polygon = self.create_polygon_pie( ((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_outer_radius_factor, (((self.widget_diameter / 2) - (self.pen.width() / 2)) * self.gauge_color_inner_radius_factor), self.scale_angle_start_value, self.scale_angle_size) gauge_rect = QRect(QPoint(0, 0), QSize(self.widget_diameter / 2 - 1, self.widget_diameter - 1)) grad = QConicalGradient(QPointF(0, 0), - self.scale_angle_size - self.scale_angle_start_value + self.angle_offset - 1) # todo definition scale color as array here for eachcolor in self.scale_polygon_colors: grad.setColorAt(eachcolor[0], eachcolor[1]) # grad.setColorAt(.00, Qt.red) # grad.setColorAt(.1, Qt.yellow) # grad.setColorAt(.15, Qt.green) # grad.setColorAt(1, Qt.transparent) painter_filled_polygon.setBrush(grad) # self.brush = QBrush(QColor(255, 0, 255, 255)) # painter_filled_polygon.setBrush(self.brush) painter_filled_polygon.drawPolygon(colored_scale_polygon)
def paintEvent(self, _): p = QPainter(self) points = [QPoint(self.width(), -1), QPoint(self.width(), self.height()), QPoint(0, self.height() / 2), QPoint(0, self.height() / 2 - 1)] grad = QLinearGradient(0, 0, 0, self.height()) grad.setColorAt(0, self.color1) grad.setColorAt(1, self.color2) p.setBrush(grad) p.setPen(QPen(Qt.NoPen)) p.drawPolygon(QPolygon(points))
def paintEvent(self, event=None): font = QFont(self.font()) font.setPointSize(font.pointSize() - 1) fm = QFontMetricsF(font) fracWidth = fm.width(FractionSlider.WSTRING) indent = fm.boundingRect("9").width() / 2.0 if not X11: fracWidth *= 1.5 span = self.width() - (FractionSlider.XMARGIN * 2) value = self.__numerator / float(self.__denominator) painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.TextAntialiasing) painter.setPen(self.palette().color(QPalette.Mid)) painter.setBrush(self.palette().brush( QPalette.AlternateBase)) painter.drawRect(self.rect()) segColor = QColor(Qt.green).dark(120) segLineColor = segColor.dark() painter.setPen(segLineColor) painter.setBrush(segColor) painter.drawRect(FractionSlider.XMARGIN, FractionSlider.YMARGIN, span, fm.height()) textColor = self.palette().color(QPalette.Text) segWidth = span / self.__denominator segHeight = fm.height() * 2 nRect = fm.boundingRect(FractionSlider.WSTRING) x = FractionSlider.XMARGIN yOffset = segHeight + fm.height() for i in range(self.__denominator + 1): painter.setPen(segLineColor) painter.drawLine(x, FractionSlider.YMARGIN, x, segHeight) painter.setPen(textColor) y = segHeight rect = QRectF(nRect) rect.moveCenter(QPointF(x, y + fm.height() / 2.0)) painter.drawText(rect, Qt.AlignCenter, QString.number(i)) y = yOffset rect.moveCenter(QPointF(x, y + fm.height() / 2.0)) painter.drawText(rect, Qt.AlignCenter, QString.number(self.__denominator)) painter.drawLine(QPointF(rect.left() + indent, y), QPointF(rect.right() - indent, y)) x += segWidth span = int(span) y = FractionSlider.YMARGIN - 0.5 triangle = [QPointF(value * span, y), QPointF((value * span) + (2 * FractionSlider.XMARGIN), y), QPointF((value * span) + FractionSlider.XMARGIN, fm.height())] painter.setPen(Qt.yellow) painter.setBrush(Qt.darkYellow) painter.drawPolygon(QPolygonF(triangle))
def drawPatchQt(self, pos, turn, invert, patch_type, image, size, foreColor, backColor, penwidth): # pylint: disable=unused-argument """ :param size: patch size """ path = self.PATH_SET[patch_type] if not path: # blank patch invert = not invert path = [(0., 0.), (1., 0.), (1., 1.), (0., 1.), (0., 0.)] polygon = QPolygonF([QPointF(x * size, y * size) for x, y in path]) rot = turn % 4 rect = [ QPointF(0., 0.), QPointF(size, 0.), QPointF(size, size), QPointF(0., size) ] rotation = [0, 90, 180, 270] nopen = QtGui.QPen(foreColor, Qt.NoPen) foreBrush = QtGui.QBrush(foreColor, Qt.SolidPattern) if penwidth > 0: pen_color = QtGui.QColor(255, 255, 255) pen = QtGui.QPen(pen_color, Qt.SolidPattern) pen.setWidth(penwidth) painter = QPainter() painter.begin(image) painter.setPen(nopen) painter.translate(pos[0] * size + penwidth / 2, pos[1] * size + penwidth / 2) painter.translate(rect[rot]) painter.rotate(rotation[rot]) if invert: # subtract the actual polygon from a rectangle to invert it poly_rect = QPolygonF(rect) polygon = poly_rect.subtracted(polygon) painter.setBrush(foreBrush) if penwidth > 0: # draw the borders painter.setPen(pen) painter.drawPolygon(polygon, Qt.WindingFill) # draw the fill painter.setPen(nopen) painter.drawPolygon(polygon, Qt.WindingFill) painter.end() return image
def paintEvent(self, event): """ Draw the QImage on screen. """ textPosX,textPosY = 10,200 painter = QPainter(self) painter.drawImage(painter.viewport(), self._image) innerFont = QFont() innerFont.setPointSize(12) painter.setFont(innerFont) painter.setPen(QColor(QtCore.Qt.white)) painter.drawText(10,180,'Current Action:') painter.drawText(10,200,self._currentMovement) self.drawMoreText(painter,10,300,['Control Buttons:', 'w,s - Walking Forwards/Backwards', 'q,e - Walking Left/Right', 'a,d - Turning Left/Right', 'x - stopping', 'Space - standing up', 'Ctrl - crouch', 'Escape,Enter - restMode, wakeUp', '1 - Grabbing small', '2 - Grabbing large', '3 - Grabbing Kuscheltier', '4 - Grabbing bottle']) self.drawMoreText(painter,self.width()-300-25,300,['Dialog Control:({})'.format(self._attitude), 'u - Introduction', 'i - Ask for object', 'h - Object is Somat', 'j - Object is Muesli', 'k - Object is Bottle', 'l - Object is Kuscheltier', 'n - Wertstoff', 'm - Altpapier', 'o - Ask for help', 'z - Ask proband to repeat sentence', 'p - Repeat task', '0(Null) - construct initial state', 't - Goodbye', 'b - thanks', '# - Start free Speech(PopUp)']) self.drawMoreText(painter,100,50,['Movement Speeds','Forward: {}'.format(self._currentSpeeds['Forward']),'Leftward: {}'.format(self._currentSpeeds['Leftward']),'CounterClockwise: {}'.format(self._currentSpeeds['CounterClockwise'])]) pen = QPen() pen.setColor(QColor(QtCore.Qt.red)) pen.setWidth(5) painter.setPen(pen) painter.drawEllipse(20,15,60,30) pen.setColor(QColor(QtCore.Qt.blue)) painter.setPen(pen) painter.drawPolygon(self.rotatePolygon(arrowPolygon,math.degrees(self._motionProxy.getAngles('HeadYaw',True)[0]),[30,20]))
def paintEvent(self, _): p = QPainter(self) points = [ QPoint(self.width(), -1), QPoint(self.width(), self.height()), QPoint(0, self.height() / 2), QPoint(0, self.height() / 2 - 1) ] grad = QLinearGradient(0, 0, 0, self.height()) grad.setColorAt(0, self.color1) grad.setColorAt(1, self.color2) p.setBrush(grad) p.setPen(QPen(Qt.NoPen)) p.drawPolygon(QPolygon(points))
def _drawIcon(self, color=Qt.black): self.setForeground(QBrush(color)) if self.isRootNode: pixmap = QPixmap(20, 20) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) pen = QPen(color) pen.setWidth(1) painter.setPen(pen) painter.setBrush(color) painter.setRenderHint(QPainter.Antialiasing) if not self.isExpanded: arrowRightPolygon = [QPoint(6,6), QPoint(6,14), QPoint(14, 10)] painter.drawPolygon(QPolygon(arrowRightPolygon)) else: arrowDownPolygon = [QPoint(6,6), QPoint(15,6), QPoint(10, 14)] painter.drawPolygon(QPolygon(arrowDownPolygon)) painter.end() self.setIcon(QIcon(pixmap))
def setSpinBoxDownIcon(self, opacity=0.6): self.buttonStyle = "spinDown" self.setToolTip("- 1") pixmap = QPixmap(250, 250) pixmap.fill(self.backgroundColor) painter = QPainter() painter.begin(pixmap) painter.setRenderHint(QPainter.Antialiasing) painter.setOpacity(opacity) brush = QBrush(self.foregroundColor) painter.setBrush(brush) pen = QPen(self.foregroundColor) painter.setPen(pen) points = QPolygonF() points.append(QPointF(125.0, 200.0)) points.append(QPointF(200.0, 70.0)) points.append(QPointF(50.0, 70.0)) painter.drawPolygon(points) painter.end() pixmap = pixmap.scaled(QSize(self.pixmapWidth, self.pixmapHeight),Qt.KeepAspectRatio, Qt.SmoothTransformation) self.setPixmap(pixmap)
def hexagon_mask(image, hexa=False, **kwargs): """ Appliquer un découpage du masque de l'image en hexagone arrondi :param image: image PIL :param hexa: False ou le rayon des arrondis de l'hexagone en pixels :return: Une image PIL dont le contour est un haxagone aux angles arrondis ou l'image originale """ if hexa is not False: try: qimage = _pil_to_qt(image) # Créer une image de la même taille que l'originale newimage = _qt_canvas(image) painter = QPainter(newimage) painter.setRenderHint(QPainter.Antialiasing, True) # Dessiner un hexagone offset = hexa * 2.0 width, height, bottom, top, t, l = qimage.width( ) - offset * 2, qimage.height( ) - offset * 2, 0.759, 0.241, offset, offset points = [ l + width / 2.0, t + 0, l + width, t + height * top, l + width, t + height * bottom, l + width / 2.0, t + height, l + 0, t + height * bottom, l + 0, t + height * top ] brush = QBrush(qimage) pen = QPen(brush, offset * 2.0, cap=Qt.RoundCap, join=Qt.RoundJoin) pen.setColor(QColor(0, 0, 0, 0)) painter.setBrush(brush) painter.setPen(pen) painter.drawPolygon(QPolygon(points)) painter.end() return _qt_to_pil(newimage) except Exception: return image else: return image
def _drawMeasurements(self): if self.selNuc is None: return painter = QPainter() painter.begin(self.imagePixmap) painter.setRenderHint(QPainter.Antialiasing) rng_thick = 3 rng_thick *= self.pix_per_um if self.activeCh == "dna": # get nuclei boundary as a polygon nucb_qpoints_e = [ Qt.QPoint(x, y) for x, y in self.selNuc.buffer(rng_thick).exterior.coords ] nucb_qpoints_i = [ Qt.QPoint(x, y) for x, y in self.selNuc.exterior.coords ] painter.setPen(QPen(QBrush(QColor('white')), 3)) painter.drawPolygon(Qt.QPolygon(nucb_qpoints_i)) painter.drawPolygon(Qt.QPolygon(nucb_qpoints_e)) nucb_poly = Qt.QPolygon(nucb_qpoints_e).subtracted( Qt.QPolygon(nucb_qpoints_i)) brush = QBrush(QtCore.Qt.BDiagPattern) brush.setColor(QColor('white')) painter.setBrush(brush) painter.setPen(QPen(QBrush(QColor('transparent')), 0)) painter.drawPolygon(nucb_poly) elif self.activeCh == "act": nuc_pen = QPen(QBrush(QColor('red')), 2) nuc_pen.setStyle(QtCore.Qt.DotLine) painter.setPen(nuc_pen) for n in [e["boundary"] for e in self._boudaries]: # get nuclei boundary as a polygon nucb_qpoints = [Qt.QPoint(x, y) for x, y in n.exterior.coords] painter.drawPolygon(Qt.QPolygon(nucb_qpoints)) for me in self.measurements: painter.setPen( QPen( QBrush(QColor(me['c'])), 2 * self.pix_per_um if me == self.selectedLine else self.pix_per_um)) pts = [Qt.QPoint(x, y) for x, y in [me['ls0'], me['ls1']]] painter.drawLine(pts[0], pts[1]) painter.end()
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock(self.edit.textCursor().position()) if self._firstPaintEvent is True: self.jumpedUP = False self.strings = self.edit.toPlainText().split("\n") self._originalTotalLine = len(self.strings) self.edit.jump_to_line(len(self.strings) - 2) elif self.jumpedUP is False: self.edit.jump_to_line(1) self.edit.verticalScrollBar().setValue(0) self.jumpedUP = True return pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get("sidebar-background", resources.COLOR_SCHEME["sidebar-background"]) foreground = resources.CUSTOM_SCHEME.get("sidebar-foreground", resources.COLOR_SCHEME["sidebar-foreground"]) pep8color = resources.CUSTOM_SCHEME.get("pep8-underline", resources.COLOR_SCHEME["pep8-underline"]) errorcolor = resources.CUSTOM_SCHEME.get("error-underline", resources.COLOR_SCHEME["error-underline"]) migrationcolor = resources.CUSTOM_SCHEME.get( "migration-underline", resources.COLOR_SCHEME["migration-underline"] ) painter.fillRect(self.rect(), QColor(background)) """ if self._firstPaintEvent is True: block = self.edit.document().findBlock(0) else: block = self.edit.firstVisibleBlock() """ block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) pat = re.compile("\s*#AppObject:") patAlexaAppImage = re.compile("\s*#AppImage:") patAlexaAppText = re.compile("\s*#AppText:") patAlexaLog = re.compile("\s*#Alexa Log") while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines error = False if settings.CHECK_STYLE and ((line_count - 1) in self._pep8Lines): painter.setPen(QColor(pep8color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.FIND_ERRORS and ((line_count - 1) in self._errorsLines): painter.setPen(QColor(errorcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.SHOW_MIGRATION_TIPS and ((line_count - 1) in self._migrationLines): painter.setPen(QColor(migrationcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True else: painter.setPen(QColor(foreground)) # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText( self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count), ) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count # Code Folding xofs = self.width() - self.foldArea painter.fillRect( xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get("fold-area", resources.COLOR_SCHEME["fold-area"])), ) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush( QColor(resources.CUSTOM_SCHEME.get("fold-arrow", resources.COLOR_SCHEME["fold-arrow"])) ) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush( QColor(resources.CUSTOM_SCHEME.get("fold-arrow", resources.COLOR_SCHEME["fold-arrow"])) ) iconPainter.drawPolygon(polygon) if self._firstPaintEvent is True: block = self.edit.document().findBlock(0) else: block = self.edit.firstVisibleBlock() # block = self.edit.firstVisibleBlock() line_count = block.blockNumber() while block.isValid(): # while line_count < 5000: line_count += 1 position = self.edit.blockBoundingGeometry(block).topLeft() + viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # block.isVisible() and if block.isVisible() and pat.match(block.text()) and block not in self._foldedAlexaObject: self._fold(line_count) self._foldedAlexaObject.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaAppImage.match(block.text()) and block not in self._foldedAlexaImage: self._fold(line_count) self._foldedAlexaImage.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaAppText.match(block.text()) and block not in self._foldedAlexaText: self._fold(line_count) self._foldedAlexaText.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaLog.match(block.text()) and block not in self._foldedAlexaLog: self._fold(line_count) self._foldedAlexaLog.append(block) self._alexaObjectsPresent = True elif pattern.match(block.text()) and block.isVisible(): if block.blockNumber() in self._foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: # block.setVisible(True) painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) # Add Bookmarks and Breakpoint elif block.blockNumber() in self._breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea ) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse(xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self._bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea ) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect(xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() block = self.edit.document().findBlock(0) line_count = 0 line_hidden = 0 while block.isValid(): line_count += 1 if not block.isVisible(): line_hidden += 1 block = block.next() endScrollBar = line_count - line_hidden self.edit.verticalScrollBar().setRange(0, endScrollBar) if self._firstPaintEvent is True: self._firstPaintEvent = False # self.updateAlexaAppObjCoords() # self.updateAlexaLogCoords() painter.end() """ #self.edit.update() if self.edit.verticalScrollBar().value() != self._oldVerticalScrollbarPosition and self._alexaObjectsPresent is True: self._oldVerticalScrollbarPosition = self.edit.verticalScrollBar().value() self.updateAlexaCoords() self.edit.update() # in this way we can refresh alexa icon position if self.edit.horizontalScrollBar().value() != self._oldHorizontalScrollbarPosition and self._alexaObjectsPresent is True: self._oldHorizontalScrollbarPosition = self.edit.horizontalScrollBar().value() self.updateAlexaCoords() self.edit.update() # in this way we can refresh alexa icon position """ self.strings = self.edit.toPlainText().split("\n") self._currentTotalLine = len(self.strings) if self._currentTotalLine != self._originalTotalLine: self._originalTotalLine = self._currentTotalLine self.updateAlexaCoords() self.edit.update() """ if self._returnPressed is True: self._returnPressed = False self.updateAlexaAppObjCoords() self.updateAlexaLogCoords() self.edit.update() if self._backspacePressed is True: self._backspacePressed = False self.strings = self.edit.toPlainText().split('\n') self._currentTotalLine = len(self.strings) if self._currentTotalLine != self._originalTotalLine: self.updateAlexaAppObjCoords() self.updateAlexaLogCoords() self.edit.update() """ if self.edit._alexaAppObjIconsCoords != self._oldAlexaAppObjIconsCoords: self._oldAlexaAppObjIconsCoords = copy.deepcopy(self.edit._alexaAppObjIconsCoords) self.edit.update() if self.edit._alexaAppImgIconsCoords != self._oldAlexaAppImgIconsCoords: self._oldAlexaAppImgIconsCoords = copy.deepcopy(self.edit._alexaAppImgIconsCoords) self.edit.update() if self.edit._alexaAppTextIconsCoords != self._oldAlexaAppTextIconsCoords: self._oldAlexaAppTextIconsCoords = copy.deepcopy(self.edit._alexaAppTextIconsCoords) self.edit.update() if self.edit._alexaLogIconsCoords != self._oldAlexaLogIconsCoords: self._oldAlexaLogIconsCoords = copy.deepcopy(self.edit._alexaLogIconsCoords) self.edit.update() selectedLine = self.edit.textCursor().selectedText() textAtCursorPos = self.edit.textCursor().block().text() try: # tmp = selectedLine.index("# AppObject") if ( pat.match(selectedLine) or patAlexaLog.match(selectedLine) or pat.match(textAtCursorPos) or patAlexaLog.match(textAtCursorPos) or patAlexaAppImage.match(selectedLine) or patAlexaAppImage.match(textAtCursorPos) or patAlexaAppText.match(selectedLine) or patAlexaAppText.match(textAtCursorPos) ) and self._keypress is True: self._keypress = False self.updateAlexaCoords() except: pass QWidget.paintEvent(self, event) """
def paintEvent(self, event): # Initialize QPainter properties painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) if self.height() <= self.width() / self.ref_aspect_ratio: v_scale = self.height() h_scale = v_scale * self.ref_aspect_ratio else: h_scale = self.width() v_scale = h_scale / self.ref_aspect_ratio # Scale all objects proportionate to window size painter.scale(h_scale / self.width_ref, v_scale / self.height_ref) painter.setClipPath(self.dial) # Don't allow objects or text to extend outside of main dial shape painter.save() # First draw main gauge background pen = QPen(painter.pen()) pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(100, 100, 100, 255)) # self.dial_bg) painter.drawPath(self.dial) # Add Minor and Major Alarm limit bars pen.setWidth(16) pen.setCapStyle(Qt.FlatCap) pen.setJoinStyle(Qt.BevelJoin) pen.setColor(Qt.yellow) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawPath(self.low_arc) painter.drawPath(self.high_arc) pen.setColor(Qt.red) painter.setPen(pen) painter.drawPath(self.lolo_arc) painter.drawPath(self.hihi_arc) painter.restore() # Display PV current value painter.save() font = QFont() font.setPixelSize(45) painter.setFont(font) sevr = self.channel.sevr.lower() if sevr == 'major': color = Qt.red elif sevr == 'minor': color = Qt.yellow elif sevr == 'invalid': color = Qt.magenta else: color = Qt.green pen.setColor(color) painter.setPen(pen) font_metric = QFontMetrics(font) painter.translate(self.dial_width / 2, self.dial_height / 2) label = self.format_label(self.channel_value) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, font_metric.height() / 2.0), label) # Display PV name painter.setFont(self.pv_label_font) pen.setColor(Qt.black) # Qt.darkCyan) pen.setWidth(1) painter.setPen(pen) # brush = QBrush(Qt.darkCyan) # painter.setBrush(brush) font_metric = QFontMetrics(self.pv_label_font) pv_label = self.channel.egu # self.channel.name + ' (' + self.channel.egu + ')' painter.drawText(QPointF(0.0 - font_metric.width(pv_label) / 2.0, (self.dial_height / 2.0) + (font_metric.height() * 1.5)), pv_label) # painter.drawPath(self.pv_label_path) painter.restore() # Next add division markers painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) pen.setWidth(2) painter.setPen(pen) for i in range(0, 31): if (i % 5) != 0: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.2, 0.0) else: painter.drawLine(-self.dial_width / 2.1, 0.0, -self.dial_width / 2.3, 0.0) painter.rotate(6.0) painter.restore() # Layout division text labels painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) pen.setColor(Qt.black) # Qt.cyan) painter.setPen(pen) font = QFont() font.setPixelSize(18) painter.setFont(font) font_metric = QFontMetrics(font) labels = linspace(self.lim_low, self.lim_hi, 7) painter.rotate(-90) for i in range(0, 7): label = self.format_label(labels[i]) painter.drawText(QPointF(0.0 - font_metric.width(label) / 2.0, -self.dial_height * 0.75), label) painter.rotate(30) painter.restore() # Draw needle at appropriate angle for data painter.save() painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.rotate(-180 * (1.0 - self.percentage)) pen.setColor(QColor(self.needle_color).darker(200)) pen.setWidth(1) painter.setPen(pen) painter.setBrush(self.needle_color) painter.drawPolygon(self.needle) painter.restore() # if self.percentage <= 0.5: # shadow = max(490 * self.percentage, 127) # needle_left_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # needle_right_color = Qt.cyan # QColor(230,230,230,255) # else: # shadow = max(125 / self.percentage, 127) # needle_left_color = Qt.cyan # QColor(230,230,230,255) # needle_right_color = QColor(0, shadow, shadow) # Qt.darkCyan # QColor(80,80,80,255) # # # Draw Highlight side of needle # pen.setWidth(1) # pen.setColor(Qt.gray) # needle_left_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_left_color) # painter.drawPolygon(self.needle_left) # # # Draw shadow side of needle # pen.setColor(Qt.gray) # needle_right_color) # painter.setPen(pen) # painter.setBrush(Qt.gray) # needle_right_color) # painter.drawPolygon(self.needle_right) # painter.restore() # Draw needle axel pin painter.save() pen.setWidth(1) pen.setColor(Qt.black) painter.setPen(pen) painter.setBrush(QColor(50, 50, 50, 255)) # self.pin_bg) painter.translate(self.dial_width / 2, self.dial_height * 0.98) painter.drawEllipse(self.pin_rect) painter.restore() # Draw glass reflection and shadow effects # painter.save() # painter.translate(self.dial_width / 2.0, self.dial_height / 2.0) # painter.setPen(Qt.NoPen) # painter.setBrush(QColor(0, 0, 0, 20)) # painter.drawEllipse(self.shadow_rect) # painter.setBrush(self.gloss_gradient) # painter.drawEllipse(self.gloss_rect) # painter.restore() painter.end()
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) width = self.width() height = self.height() if self.dynamic_resize: knob_radius = self.dynamic_knob_radius else: knob_radius = self.knob_radius # ensure that the center point is in the middle of a pixel to ensure # that exact vertial and horizantal ticks are drawn exactly 1px wide x = math.floor(width / 2.0) + 0.5 y = math.floor(height / 2.0) + 0.5 if DEBUG: painter.fillRect(0, 0, width, height, Qt.yellow) painter.translate(x, y) if self.knob_style == KnobWidget.STYLE_NEEDLE: r = min(x, y) - 1 painter.setPen(Qt.white) painter.setBrush(Qt.white) painter.drawEllipse(QPoint(0, 0), r, r) angle = self.value_factor * self.total_angle - (self.total_angle / 2.0) # draw base knob or needle spike if self.knob_style == KnobWidget.STYLE_ROUND: painter.setPen(self.border_color) if self.pressed: gradient = QRadialGradient(0, 0, knob_radius) gradient.setColorAt(0, self.base_color_pressed) gradient.setColorAt(0.85, self.base_color) gradient.setColorAt(1, self.base_color) painter.setBrush(gradient) else: painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), knob_radius, knob_radius) elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.save() painter.rotate(angle) painter.setPen(self.needle_color) painter.setBrush(self.needle_color) needle = QPolygonF() needle.append(QPointF(self.needle_base_radius * 0.6, 0)) needle.append(QPointF(0, -knob_radius)) needle.append(QPointF(-self.needle_base_radius * 0.6, 0)) painter.drawPolygon(needle) painter.restore() # draw knob mark or needle base if self.knob_style == KnobWidget.STYLE_ROUND: painter.save() painter.rotate(angle) painter.setPen(QPen(self.mark_color, 2)) painter.drawLine(0, -knob_radius * 0.4, 0, -knob_radius * 0.8) painter.restore() elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.setPen(self.border_color) painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), self.needle_base_radius, self.needle_base_radius) if self.scale_visible: painter.setPen(Qt.black) # draw scale arc if self.scale_arc_visible: painter.drawArc(-knob_radius - self.knob_to_scale, -knob_radius - self.knob_to_scale, knob_radius * 2 + self.knob_to_scale * 2, knob_radius * 2 + self.knob_to_scale * 2, (90 + self.total_angle / 2) * 16, -self.total_angle * 16) # draw scale ticks def value_to_angle(value): return (float(value - self.minimum_value) / self.value_range) * self.total_angle - (self.total_angle / 2.0) value = self.minimum_value while value <= self.maximum_value: angle = value_to_angle(value) painter.save() painter.rotate(value_to_angle(value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_large) if self.scale_text_visible: p = painter.worldTransform().map(QPoint(0, -knob_radius - \ self.knob_to_scale - \ self.tick_size_large - \ self.tick_to_text - \ self.text_radius)) painter.restore() if self.scale_text_visible: if DEBUG: painter.save() painter.setPen(QColor(255, 0, 0, 50)) painter.setBrush(QColor(255, 0, 0, 50)) painter.drawEllipse(QPoint(p.x() - x, p.y() - y), self.text_radius, self.text_radius) painter.restore() painter.drawText(p.x() - x - 30, p.y() - y - 30, 60, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, str(value)) for i in range(1, self.scale_step_divisions): sub_value = value + (float(self.scale_step_size) * i) / self.scale_step_divisions if sub_value > self.maximum_value: break painter.save() painter.rotate(value_to_angle(sub_value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_small) painter.restore() value += self.scale_step_size if self.title_text != None: painter.drawText(-knob_radius, knob_radius - 30, knob_radius * 2, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, self.title_text)
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1, -1) self._painter.translate(0, -canvas.height()) Renderer.set_canvas(self, canvas) def _get_canvas_size(self, pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs, ys = zip(transform.map(0.0, 0.0), transform.map(0.0, float(self.size[1])), transform.map(float(self.size[0]), float(self.size[1])), transform.map(float(self.size[0]), 0.0)) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin // self._grid_spacing), int(xmax // self._grid_spacing + 1)) y_ticks = (int(ymin // self._grid_spacing), int(ymax // self._grid_spacing + 1)) self._painter.drawLines([ QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks) ]) self._painter.drawLines([ QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks) ]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor, factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx, dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0, 0, self.size[0], self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self, color): """Sets the line color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(self.__qcolor(color)) def set_brush(self, color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self, points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon( QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb=None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx - ra, cy - ra, 2 * ra, 2 * rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x, y, w, h)) def draw_text(self, text, x, y, bgcolor=0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1, y1, x2, y2))
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get('sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) painter.fillRect(self.rect(), QColor(background)) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines painter.setPen(QColor(foreground)) error = False checkers = sorted(self._neditable.registered_checkers, key=lambda x: x[2], reverse=True) for items in checkers: checker, color, _ = items if (line_count - 1) in checker.checks: painter.setPen(QColor(color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True break # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText(self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) self.calculate_docstring_block_fold() block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if pattern.match(block.text()) and block.isVisible(): can_fold = True if self.patComment.match(block.text()) and \ (block.blockNumber() in self._endDocstringBlocks): can_fold = False if can_fold: if block.blockNumber() in self.foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint if block.blockNumber() in self.breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self.bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() painter.end() QWidget.paintEvent(self, event)
def drawImage(self, imageid): cache = image_cache.cache cellColoring = self.cellColoring wallColoring = self.wallColoring pointColoring = self.pointColoring ellipsisDraw = self.ellipsisDraw overSampling = self.overSampling extraDrawing = self.extraDrawing bgColor = self.bgColor.rgb() result = self.result if self.result_type == "Data": data = result img_name = result.images_name[imageid] else: data = result.data img_name = result.images[imageid] #scale = data.images_scale[img_name] min_scale = data.minScale() img = cache.image(data.image_path(img_name)) img_data = data[img_name] size = self._crop.size() pix = QImage(size*overSampling, QImage.Format_ARGB32) pix.fill(bgColor) painter = QPainter() if not painter.begin(pix): self.abort("Cannot create painter on QImage") return None, None, None painter.setRenderHints(QPainter.SmoothPixmapTransform, True) painter.setRenderHints(QPainter.Antialiasing, True) if overSampling > 1: painter.scale(overSampling, overSampling) painter.translate(-self._crop.topLeft()) painter.save() painter.translate(self.translate) log_debug("Translating: %gx%g" % (self.translate.x(), self.translate.y()) ) painter.scale(1/min_scale, 1/min_scale) painter.save() matrix = img_data.matrix() painter.setWorldTransform(matrix, True) painter.drawImage(QPoint(0,0), img) painter.restore() #pt_matrix = QTransform() #pt_matrix.scale(1/min_scale, 1/min_scale) #painter.setTransform(pt_matrix, True) cellColoring.startImage(painter, imageid) wallColoring.startImage(painter, imageid) for ed in extraDrawing: ed.startImage(painter, imageid) if self.result_type == "Growth": cells = result.cells[imageid] walls = result.walls[imageid] else: cells = img_data.cells walls = set() for cid in img_data.cells: pts = [ pt for pt in data.cells[cid] if pt in img_data ] if len(pts) > 1: for i in range(len(pts)): walls.add(data.wallId(pts[i-1], pts[i])) # Now, draw the cells and the ellipsis for cid in cells: painter.setPen(Qt.NoPen) color = cellColoring(imageid, cid) painter.setBrush(color) pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1,p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1,p2]) ppts.append(ppts[0]) poly = QPolygonF(ppts) painter.drawPolygon(poly) # And draw the walls wallThickness = self.wallThickness*min_scale for wid in walls: color = wallColoring(imageid, wid) if color.alpha() > 0: pen = QPen(color) pen.setWidthF(wallThickness) painter.setPen(pen) pts = [img_data[wid[0]]] + img_data.walls[wid[0], wid[1]] + [img_data[wid[1]]] #painter.drawLine(img_data[wid[0]], img_data[wid[1]]) painter.drawPolyline(*pts) # Then, draw the points pointSize = self.pointSize*min_scale pointLineColor = self.pointLineColor pointLineThickness = self.pointLineThickness*min_scale log_debug("pointSize = %g" % pointSize) for pid in img_data: color = pointColoring(imageid, pid) if color.alpha() > 0: pen = QPen(pointLineColor) pen.setWidthF(pointLineThickness) brush = QBrush(color) painter.setPen(pen) painter.setBrush(brush) pos = img_data[pid] rect = QRectF(pos.x()-pointSize, pos.y()-pointSize, 2*pointSize, 2*pointSize) painter.drawEllipse(rect) if ellipsisDraw.plot: for cid in cells: pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1,p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1,p2]) ppts.append(ppts[0]) #poly = QPolygonF(ppts) #painter.drawPolygon(poly) ellipsisDraw(painter, imageid, cid, ppts, min_scale) # At last, draw the extra data for ed in extraDrawing: ed(painter, imageid) tr = painter.worldTransform() painter.restore() pic_w = wallColoring.finalizeImage(painter, imageid, tr, self.crop) pic_c = cellColoring.finalizeImage(painter, imageid, tr, self.crop) for ed in extraDrawing: ed.finalizeImage(painter, imageid, tr, self.crop) painter.end() return pix, pic_w, pic_c
def drawImage(self, imageid): cache = image_cache.cache cellColoring = self.cellColoring wallColoring = self.wallColoring pointColoring = self.pointColoring ellipsisDraw = self.ellipsisDraw overSampling = self.overSampling extraDrawing = self.extraDrawing bgColor = self.bgColor.rgb() result = self.result if self.result_type == "Data": data = result img_name = result.images_name[imageid] else: data = result.data img_name = result.images[imageid] #scale = data.images_scale[img_name] min_scale = data.minScale() img = cache.image(data.image_path(img_name)) img_data = data[img_name] size = self._crop.size() pix = QImage(size * overSampling, QImage.Format_ARGB32) pix.fill(bgColor) painter = QPainter() if not painter.begin(pix): self.abort("Cannot create painter on QImage") return None, None, None painter.setRenderHints(QPainter.SmoothPixmapTransform, True) painter.setRenderHints(QPainter.Antialiasing, True) if overSampling > 1: painter.scale(overSampling, overSampling) painter.translate(-self._crop.topLeft()) painter.save() painter.translate(self.translate) log_debug("Translating: %gx%g" % (self.translate.x(), self.translate.y())) painter.scale(1 / min_scale, 1 / min_scale) painter.save() matrix = img_data.matrix() painter.setWorldTransform(matrix, True) painter.drawImage(QPoint(0, 0), img) painter.restore() #pt_matrix = QTransform() #pt_matrix.scale(1/min_scale, 1/min_scale) #painter.setTransform(pt_matrix, True) cellColoring.startImage(painter, imageid) wallColoring.startImage(painter, imageid) for ed in extraDrawing: ed.startImage(painter, imageid) if self.result_type == "Growth": cells = result.cells[imageid] walls = result.walls[imageid] else: cells = img_data.cells walls = set() for cid in img_data.cells: pts = [pt for pt in data.cells[cid] if pt in img_data] if len(pts) > 1: for i in range(len(pts)): walls.add(data.wallId(pts[i - 1], pts[i])) # Now, draw the cells and the ellipsis for cid in cells: painter.setPen(Qt.NoPen) color = cellColoring(imageid, cid) painter.setBrush(color) pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1, p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1, p2]) ppts.append(ppts[0]) poly = QPolygonF(ppts) painter.drawPolygon(poly) # And draw the walls wallThickness = self.wallThickness * min_scale for wid in walls: color = wallColoring(imageid, wid) if color.alpha() > 0: pen = QPen(color) pen.setWidthF(wallThickness) painter.setPen(pen) pts = [img_data[wid[0]] ] + img_data.walls[wid[0], wid[1]] + [img_data[wid[1]]] #painter.drawLine(img_data[wid[0]], img_data[wid[1]]) painter.drawPolyline(*pts) # Then, draw the points pointSize = self.pointSize * min_scale pointLineColor = self.pointLineColor pointLineThickness = self.pointLineThickness * min_scale log_debug("pointSize = %g" % pointSize) for pid in img_data: color = pointColoring(imageid, pid) if color.alpha() > 0: pen = QPen(pointLineColor) pen.setWidthF(pointLineThickness) brush = QBrush(color) painter.setPen(pen) painter.setBrush(brush) pos = img_data[pid] rect = QRectF(pos.x() - pointSize, pos.y() - pointSize, 2 * pointSize, 2 * pointSize) painter.drawEllipse(rect) if ellipsisDraw.plot: for cid in cells: pts = data.cellAtTime(cid, img_data.index) if pts: pts.append(pts[0]) ppts = [] for p1, p2 in zip(pts[:-1], pts[1:]): ppts.append(img_data[p1]) ppts.extend(img_data.walls[p1, p2]) ppts.append(ppts[0]) #poly = QPolygonF(ppts) #painter.drawPolygon(poly) ellipsisDraw(painter, imageid, cid, ppts, min_scale) # At last, draw the extra data for ed in extraDrawing: ed(painter, imageid) tr = painter.worldTransform() painter.restore() pic_w = wallColoring.finalizeImage(painter, imageid, tr, self.crop) pic_c = cellColoring.finalizeImage(painter, imageid, tr, self.crop) for ed in extraDrawing: ed.finalizeImage(painter, imageid, tr, self.crop) painter.end() return pix, pic_w, pic_c
def paintEvent(self, event = None): LogicalSize = 100.0 def logicalFromPhysical(length, side): return (length / side) * LogicalSize fm = QFontMetricsF(self.font()) ymargin = ((LogicalSize / 30.0) + logicalFromPhysical(self.leftSpinBox.height(), self.height())) ymax = (LogicalSize - logicalFromPhysical(fm.height() * 2, self.height())) width = LogicalSize / 4.0 cx, cy = LogicalSize / 2.0, LogicalSize / 3.0 ax, ay = cx - (2 * width), ymargin bx, by = cx - width, ay dx, dy = cx + width, ay ex, ey = cx + (2 * width), ymargin fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0) gx, gy = fx, ymax hx, hy = cx - (width / 2), ymax ix, iy = hx, fy painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) side = min(self.width(), self.height()) painter.setViewport((self.width() - side) / 2, (self.height() - side) / 2, side, side) painter.setWindow(0, 0, LogicalSize, LogicalSize) painter.setPen(Qt.NoPen) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) a = self.leftSpinBox.value() gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white)) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy])) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) b = self.rightSpinBox.value() gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white)) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy])) if (a + b) == 0: color = QColor(Qt.white) else: ashare = (a / (a + b)) * 255.0 bshare = 255.0 - ashare color = QColor(ashare, 0, bshare) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) gradient.setColorAt(1, color) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy])) painter.setPen(Qt.black) painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy])) painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey])) painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
class QtRenderer(Renderer): """An implementation of :class:`~renderer.Renderer` for PyQt4. This renderer will draw on any `QPaintDevice` """ def __init__(self, paint_device): """Creates a new renderer based on a QPaintDevice pd""" self._grid_pen = QPen(QColor(0x808080)) self._grid_pen.setStyle(Qt.DashLine) self._painter = None Renderer.__init__(self, paint_device) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent""" if self._painter is not None: self._painter.restore() self._painter.restore() self._painter.end() self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1,-1) self._painter.translate(0,-canvas.height()) Renderer.set_canvas(self,canvas) def _get_canvas_size(self,pd): """Get the canvas size tuple (width,height)""" return (pd.width(), pd.height()) def push_state(self): """Store the current state on the stack. Current state includes default pose, pen and brush""" ### FIXME store things self._painter.save() def pop_state(self): """Restore the last saved state from the stack The state includes default pose, pen and brush""" ### FIXME store things self._painter.restore() def _calculate_bounds(self): transform = self._painter.worldTransform().inverted()[0] xs,ys = zip( transform.map(0.0,0.0), transform.map(0.0,float(self.size[1])), transform.map(float(self.size[0]),float(self.size[1])), transform.map(float(self.size[0]),0.0) ) self._bounds = (min(xs), min(ys), max(xs), max(ys)) def _draw_grid(self): self.reset_pose() self._painter.setPen(self._grid_pen) xmin, ymin, xmax, ymax = self._bounds # Determine min/max x & y line indices: x_ticks = (int(xmin//self._grid_spacing), int(xmax//self._grid_spacing + 1)) y_ticks = (int(ymin//self._grid_spacing), int(ymax//self._grid_spacing + 1)) self._painter.drawLines( [QLineF(xmin, i * self._grid_spacing, xmax, i * self._grid_spacing) for i in range(*y_ticks)]) self._painter.drawLines( [QLineF(i * self._grid_spacing, ymin, i * self._grid_spacing, ymax) for i in range(*x_ticks)]) def scale(self, factor): """Scale drawing operations by factor To be implemented in subclasses.""" self._painter.scale(factor,factor) def rotate(self, angle): """Rotate canvas by angle (in radians) To be implemented in subclasses.""" self._painter.rotate(degrees(angle)) def translate(self, dx, dy): """Translate canvas by dx, dy To be implemented in subclasses.""" self._painter.translate(dx,dy) def clear_screen(self): """Erases the current screen with a white brush""" self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0,0,self.size[0],self.size[1]) self._painter.restore() Renderer.clear_screen(self) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color""" c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self,color=0, thickness=0): """Sets the line color and thickness. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(QPen(self.__qcolor(color),thickness)) def set_brush(self,color): """Sets the fill color. Color is interpreted as 0xAARRGGBB.""" if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self,points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array.""" self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, cx, cy, ra, rb = None): """Draws an ellipse.""" if rb is None: rb = ra self._painter.drawEllipse(QRectF(cx-ra,cy-ra,2*ra,2*rb)) def draw_rectangle(self, x, y, w, h): """Draws a rectangle.""" self._painter.drawRect(QRectF(x,y,w,h)) def draw_text(self, text, x, y, bgcolor = 0): """Draws a text string at the defined position.""" pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2)""" self._painter.drawLine(QLineF(x1,y1,x2,y2))
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) if self._firstPaintEvent is True: self.jumpedUP = False self.strings = self.edit.toPlainText().split('\n') self._originalTotalLine = len(self.strings) self.edit.jump_to_line(len(self.strings) - 2) elif self.jumpedUP is False: self.edit.jump_to_line(1) self.edit.verticalScrollBar().setValue(0) self.jumpedUP = True return pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get( 'sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get( 'sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) pep8color = resources.CUSTOM_SCHEME.get( 'pep8-underline', resources.COLOR_SCHEME['pep8-underline']) errorcolor = resources.CUSTOM_SCHEME.get( 'error-underline', resources.COLOR_SCHEME['error-underline']) migrationcolor = resources.CUSTOM_SCHEME.get( 'migration-underline', resources.COLOR_SCHEME['migration-underline']) painter.fillRect(self.rect(), QColor(background)) ''' if self._firstPaintEvent is True: block = self.edit.document().findBlock(0) else: block = self.edit.firstVisibleBlock() ''' block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) pat = re.compile('\s*#.*AppObject:') patAlexaAppImage = re.compile('\s*#.*AppImage:') patAlexaAppText = re.compile('\s*#.*AppText:') patAlexaLog = re.compile('\s*##.*Alexa Log') while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines error = False if settings.CHECK_STYLE and \ ((line_count - 1) in self._pep8Lines): painter.setPen(QColor(pep8color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.FIND_ERRORS and \ ((line_count - 1) in self._errorsLines): painter.setPen(QColor(errorcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.SHOW_MIGRATION_TIPS and \ ((line_count - 1) in self._migrationLines): painter.setPen(QColor(migrationcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True else: painter.setPen(QColor(foreground)) # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText( self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding xofs = self.width() - self.foldArea painter.fillRect( xofs, 0, self.foldArea, self.height(), QColor( resources.CUSTOM_SCHEME.get( 'fold-area', resources.COLOR_SCHEME['fold-area']))) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush( QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush( QColor( resources.CUSTOM_SCHEME.get( 'fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) if self._firstPaintEvent is True: block = self.edit.document().findBlock(0) else: block = self.edit.firstVisibleBlock() #block = self.edit.firstVisibleBlock() line_count = block.blockNumber() while block.isValid(): #while line_count < 5000: line_count += 1 position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break #block.isVisible() and if block.isVisible() and pat.match( block.text()) and block not in self._foldedAlexaObject: self._fold(line_count) self._foldedAlexaObject.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaAppImage.match( block.text()) and block not in self._foldedAlexaImage: self._fold(line_count) self._foldedAlexaImage.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaAppText.match( block.text()) and block not in self._foldedAlexaText: self._fold(line_count) self._foldedAlexaText.append(block) self._alexaObjectsPresent = True elif block.isVisible() and patAlexaLog.match( block.text()) and block not in self._foldedAlexaLog: self._fold(line_count) self._foldedAlexaLog.append(block) self._alexaObjectsPresent = True elif pattern.match(block.text()) and block.isVisible(): if block.blockNumber() in self._foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: #block.setVisible(True) painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint elif block.blockNumber() in self._breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse(xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self._bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect(xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() block = self.edit.document().findBlock(0) line_count = 0 line_hidden = 0 while block.isValid(): line_count += 1 if not block.isVisible(): line_hidden += 1 block = block.next() endScrollBar = line_count - line_hidden self.edit.verticalScrollBar().setRange(0, endScrollBar) if self._firstPaintEvent is True: self._firstPaintEvent = False #self.updateAlexaAppObjCoords() #self.updateAlexaLogCoords() painter.end() ''' #self.edit.update() if self.edit.verticalScrollBar().value() != self._oldVerticalScrollbarPosition and self._alexaObjectsPresent is True: self._oldVerticalScrollbarPosition = self.edit.verticalScrollBar().value() self.updateAlexaCoords() self.edit.update() # in this way we can refresh alexa icon position if self.edit.horizontalScrollBar().value() != self._oldHorizontalScrollbarPosition and self._alexaObjectsPresent is True: self._oldHorizontalScrollbarPosition = self.edit.horizontalScrollBar().value() self.updateAlexaCoords() self.edit.update() # in this way we can refresh alexa icon position ''' self.strings = self.edit.toPlainText().split('\n') self._currentTotalLine = len(self.strings) if self._currentTotalLine != self._originalTotalLine: self._originalTotalLine = self._currentTotalLine self.updateAlexaCoords() self.edit.update() ''' if self._returnPressed is True: self._returnPressed = False self.updateAlexaAppObjCoords() self.updateAlexaLogCoords() self.edit.update() if self._backspacePressed is True: self._backspacePressed = False self.strings = self.edit.toPlainText().split('\n') self._currentTotalLine = len(self.strings) if self._currentTotalLine != self._originalTotalLine: self.updateAlexaAppObjCoords() self.updateAlexaLogCoords() self.edit.update() ''' if self.edit._alexaAppObjIconsCoords != self._oldAlexaAppObjIconsCoords: self._oldAlexaAppObjIconsCoords = copy.deepcopy( self.edit._alexaAppObjIconsCoords) self.edit.update() if self.edit._alexaAppImgIconsCoords != self._oldAlexaAppImgIconsCoords: self._oldAlexaAppImgIconsCoords = copy.deepcopy( self.edit._alexaAppImgIconsCoords) self.edit.update() if self.edit._alexaAppTextIconsCoords != self._oldAlexaAppTextIconsCoords: self._oldAlexaAppTextIconsCoords = copy.deepcopy( self.edit._alexaAppTextIconsCoords) self.edit.update() if self.edit._alexaLogIconsCoords != self._oldAlexaLogIconsCoords: self._oldAlexaLogIconsCoords = copy.deepcopy( self.edit._alexaLogIconsCoords) self.edit.update() selectedLine = self.edit.textCursor().selectedText() textAtCursorPos = self.edit.textCursor().block().text() try: #tmp = selectedLine.index("# AppObject") if (pat.match(selectedLine) or patAlexaLog.match(selectedLine) or \ pat.match(textAtCursorPos) or patAlexaLog.match(textAtCursorPos) or \ patAlexaAppImage.match(selectedLine) or patAlexaAppImage.match(textAtCursorPos) or\ patAlexaAppText.match(selectedLine) or patAlexaAppText.match(textAtCursorPos)) and \ self._keypress is True: self._keypress = False self.updateAlexaCoords() except: pass QWidget.paintEvent(self, event) '''
def paintEvent(self, event): super().paintEvent(event) painter = QPainter(self.viewport()) painter.setBrush(QColor(100, 100, 100, 100)) painter.setRenderHints(self.renderHints()) painter.drawPolygon(self.viewPolygon())
def paintEvent(self, event=None): LogicalSize = 100.0 def logicalFromPhysical(length, side): return (length / side) * LogicalSize fm = QFontMetricsF(self.font()) ymargin = ( (LogicalSize / 30.0) + logicalFromPhysical(self.leftSpinBox.height(), self.height())) ymax = (LogicalSize - logicalFromPhysical(fm.height() * 2, self.height())) width = LogicalSize / 4.0 cx, cy = LogicalSize / 2.0, LogicalSize / 3.0 ax, ay = cx - (2 * width), ymargin bx, by = cx - width, ay dx, dy = cx + width, ay ex, ey = cx + (2 * width), ymargin fx, fy = cx + (width / 2), cx + (LogicalSize / 24.0) gx, gy = fx, ymax hx, hy = cx - (width / 2), ymax ix, iy = hx, fy painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) side = min(self.width(), self.height()) painter.setViewport((self.width() - side) / 2, (self.height() - side) / 2, side, side) painter.setWindow(0, 0, LogicalSize, LogicalSize) painter.setPen(Qt.NoPen) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) a = self.leftSpinBox.value() gradient.setColorAt(1, (Qt.red if a != 0 else Qt.white)) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([ax, ay, bx, by, cx, cy, ix, iy])) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) b = self.rightSpinBox.value() gradient.setColorAt(1, (Qt.blue if b != 0 else Qt.white)) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([cx, cy, dx, dy, ex, ey, fx, fy])) if (a + b) == 0: color = QColor(Qt.white) else: ashare = (a / (a + b)) * 255.0 bshare = 255.0 - ashare color = QColor(ashare, 0, bshare) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 100)) gradient.setColorAt(0, Qt.white) gradient.setColorAt(1, color) painter.setBrush(QBrush(gradient)) painter.drawPolygon(QPolygon([cx, cy, fx, fy, gx, gy, hx, hy, ix, iy])) painter.setPen(Qt.black) painter.drawPolyline(QPolygon([ax, ay, ix, iy, hx, hy])) painter.drawPolyline(QPolygon([gx, gy, fx, fy, ex, ey])) painter.drawPolyline(QPolygon([bx, by, cx, cy, dx, dy]))
testimage = QImage(500, 500, QImage.Format_ARGB32_Premultiplied) # initialize a black background testimage.fill(0xFF000000) # draw some things in the image testpainter = QPainter(testimage) testpainter.setBrush(QBrush(QColor(0, 255, 0, 128), Qt.SolidPattern)) testpainter.setPen( QPen(QBrush(QColor(255, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin)) testpainter.drawRect(QRectF(5.0, 255.0, 240.0, 240.0)) testpainter.setBrush(QBrush(QColor(0, 0, 255, 255), Qt.SolidPattern)) testpainter.setPen( QPen(QBrush(QColor(0, 0, 0, 255), Qt.SolidPattern), 5.0, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) testpainter.drawPolygon( QPolygonF([ QPointF(.25 * ptx, .25 * pty + 250) for (ptx, pty) in pentagonpts ])) testpainter.setBrush(Qt.NoBrush) testpainter.setPen( QPen(QBrush(QColor(255, 255, 255, 255), Qt.SolidPattern), 3.0, Qt.DashLine, Qt.RoundCap, Qt.RoundJoin)) testpainter.drawPolyline( QPolygonF([QPointF(pts, pty) for (pts, pty) in linepts])) testpainter.end() # add the image command testimgwidth = testimage.width() testimgheight = testimage.height() testimgstride = testimage.bytesPerLine() # not a good way to get the pixel data testimgdata = bytearray(testimgheight * testimgstride) k = 0
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get('sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) pep8color = resources.CUSTOM_SCHEME.get('pep8-underline', resources.COLOR_SCHEME['pep8-underline']) errorcolor = resources.CUSTOM_SCHEME.get('error-underline', resources.COLOR_SCHEME['error-underline']) painter.fillRect(self.rect(), QColor(background)) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines error = False if settings.CHECK_STYLE and \ ((line_count - 1) in self._pep8Lines): painter.setPen(QColor(pep8color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.FIND_ERRORS and \ ((line_count - 1) in self._errorsLines): painter.setPen(QColor(errorcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True else: painter.setPen(QColor(foreground)) # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText(self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if pattern.match(block.text()) and block.isVisible(): if block.blockNumber() in self._foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint elif block.blockNumber() in self._breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self._bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() painter.end() QWidget.paintEvent(self, event)
class QtRenderer(Renderer): def __init__(self, pd): """Creates a new renderer based on a QPaintDevice pd """ self._defpose = Pose() # The pose in the bottom-left corner self._zoom = 1 # The zooming factor self._zoom_c = False # Whether the scaling is done from center Renderer.__init__(self, (pd.width(), pd.height()), pd) def set_canvas(self, canvas): """Tell the renderer to draw on canvas The type of canvas is implementation-dependent """ self._paintdevice = canvas self._painter = QPainter(canvas) self._painter.setRenderHint(QPainter.Antialiasing) # invert the y axis self._painter.scale(1,-1) self._painter.translate(0,-canvas.height()) self.set_pen(None) # push the default state self._painter.save() self._painter.save() def set_zoom(self, zoom_level): self._zoom = float(zoom_level) self.__update_default_state() def __update_default_state(self): self._painter.restore() # Reset state self._painter.restore() # Set zoom to 1 self._painter.save() # Re-save the zoom-1 if self._zoom_c: self._painter.translate(self.size[0]/2,self.size[1]/2) self._painter.scale(self._zoom,self._zoom) self._painter.rotate(degrees(-self._defpose.theta)) self._painter.translate(-self._defpose.x, -self._defpose.y) self._painter.save() # Save the zoomed state self.clear_screen() def __set_scr_pose(self,pose): self._defpose = pose self.__update_default_state() self.clear_screen() def set_screen_pose(self, pose): self._zoom_c = False self.__set_scr_pose(pose) def set_screen_center_pose(self, pose): self._zoom_c = True self.__set_scr_pose(pose) def clear_screen(self): self._painter.save() self._painter.resetTransform() self.set_pen(0xFFFFFF) self.set_brush(0xFFFFFF) self.draw_rectangle(0,0,self.size[0],self.size[1]) self._painter.restore() def __delete__(self): self._painter.restore() self._painter.restore() def reset_pose(self): """Resets the renderer to world coordinates """ self._painter.restore() self._painter.save() def add_pose(self,pose): """Add a pose transformation to the current transformation """ self._painter.translate(pose.x,pose.y) self._painter.rotate(degrees(pose.theta)) @staticmethod def __qcolor(color): """Returns qcolor for a given ARGB color """ c = QColor(color) if color > 0xFFFFFF: c.setAlpha((color >> 24) & 0xFF) return c def set_pen(self,color): """Sets the line color. Color is interpreted as 0xAARRGGBB. """ if color is None: self._painter.setPen(Qt.NoPen) else: self._painter.setPen(self.__qcolor(color)) def set_brush(self,color): """Sets the fill color. Color is interpreted as 0xAARRGGBB. """ if color is None: self._painter.setBrush(Qt.NoBrush) else: self._painter.setBrush(self.__qcolor(color)) def draw_polygon(self,points): """Draws a polygon. Expects a list of points as a list of tuples or as a numpy array. """ self._painter.drawPolygon(QPolygonF([QPointF(*point[:2]) for point in points])) def draw_ellipse(self, x, y, w, h): """Draws an ellipse. """ self._painter.drawEllipse(x,y,w,h) def draw_rectangle(self, x, y, w, h): """Draws a rectangle. """ self._painter.drawRect(x,y,w,h) def draw_text(self, text, x, y, bgcolor = 0): """Draws a text string at the defined position. """ pass def draw_line(self, x1, y1, x2, y2): """Draws a line using the current pen from (x1,y1) to (x2,y2) """ pass
def drawArrow(element, painter, option): """ :type element: QStyle.PrimitiveElement :type painter: QPainter :type option: QStyleOption """ # From windows style but modified to enable AA if option.rect.width() <= 1 or option.rect.height() <= 1: return r = option.rect size = min(r.height(), r.width()) pixmap = QPixmap() pixmapName = "arrow-{}-{}-{}-{}-{}".format("$qt_ia", int(option.state), element, size, option.palette.cacheKey()) if not QPixmapCache.find(pixmapName, pixmap): border = int(size / 5) sqsize = int(2 * (size / 2)) image = QImage(sqsize, sqsize, QImage.Format_ARGB32) image.fill(Qt.transparent) imagePainter = QPainter(image) imagePainter.setRenderHint(QPainter.Antialiasing, True) imagePainter.translate(0.5, 0.5) a = QPolygon() if element == QStyle.PE_IndicatorArrowUp: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowDown: a.setPoints(3, border, sqsize / 2, sqsize / 2, sqsize - border, sqsize - border, sqsize / 2) elif element == QStyle.PE_IndicatorArrowRight: a.setPoints(3, sqsize - border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) elif element == QStyle.PE_IndicatorArrowLeft: a.setPoints(3, border, sqsize / 2, sqsize / 2, border, sqsize / 2, sqsize - border) bsx = 0 bsy = 0 if option.state & QStyle.State_Sunken: bsx = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftHorizontal) bsy = QApplication.style().pixelMetric(QStyle.PM_ButtonShiftVertical) bounds = a.boundingRect() sx = int(sqsize / 2 - bounds.center().x() - 1) sy = int(sqsize / 2 - bounds.center().y() - 1) imagePainter.translate(sx + bsx, sy + bsy) if not (option.state & QStyle.State_Enabled): foreGround = QColor(150, 150, 150, 150) imagePainter.setBrush(option.palette.mid().color()) imagePainter.setPen(option.palette.mid().color()) else: shadow = QColor(0, 0, 0, 100) imagePainter.translate(0, 1) imagePainter.setPen(shadow) imagePainter.setBrush(shadow) foreGround = QColor(255, 255, 255, 210) imagePainter.drawPolygon(a) imagePainter.translate(0, -1) imagePainter.setPen(foreGround) imagePainter.setBrush(foreGround) imagePainter.drawPolygon(a) imagePainter.end() pixmap = QPixmap.fromImage(image) QPixmapCache.insert(pixmapName, pixmap) xOffset = int(r.x() + (r.width() - size) / 2) yOffset = int(r.y() + (r.height() - size) / 2) painter.drawPixmap(xOffset, yOffset, pixmap)
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) painter = QPainter(self) painter.fillRect(self.rect(), Qt.lightGray) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines error = False if settings.CHECK_STYLE and \ ((line_count - 1) in self._pep8Lines): painter.setPen(Qt.darkYellow) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.FIND_ERRORS and \ ((line_count - 1) in self._errorsLines): painter.setPen(Qt.red) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True else: painter.setPen(Qt.black) # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText(self.width() - self.foldArea - \ font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + \ font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if self.pat.match(unicode(block.text())) and block.isVisible(): if block.blockNumber() in self._foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint elif block.blockNumber() in self._breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self._bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next() painter.end() QWidget.paintEvent(self, event)