def __init__( self, painter: QPainter, x1: int, y1: int, x2: int, y2: int, event: AssEvent, is_selected: bool, ) -> None: self.event = event self.text_width = painter.fontMetrics().width(self.text) self.text_height = painter.fontMetrics().capHeight() self.x1 = x1 self.x2 = x2 self.y1 = y1 self.y2 = y2 self.label_x1 = x1 self.label_y1 = y1 self.label_x2 = x1 + min(x2 - x1, self.text_margin * 2 + self.text_width) self.label_y2 = self.text_margin * 2 + self.text_height self.label_is_visible = (x2 - x1) >= 2 * self.text_margin + self.text_width self.is_selected = is_selected
def __init__( self, painter: QtGui.QPainter, x1: int, x2: int, event: AssEvent ) -> None: self.event = event self.text_width = painter.fontMetrics().width(self.text) self.text_height = painter.fontMetrics().capHeight() self.x1 = x1 self.y1 = 0 self.x2 = x1 + min(x2 - x1, self.text_margin * 2 + self.text_width) self.y2 = self.text_margin * 2 + self.text_height self.is_visible = (x2 - x1) >= 2 * self.text_margin + self.text_width
def __AutoShrinkFont(self, p: QPainter, rect: QRect, txt: str): # 循环减小字体适应宽度 c_Font = p.font() c_Size = c_Font.pointSize() fm = p.fontMetrics() w = fm.width(txt) r_w = rect.width() while w > r_w: c_Size -= 1 c_Font.setPointSize(c_Size) p.setFont(c_Font) fm = p.fontMetrics() w = fm.width(txt)
def paintEvent(self, event: QPaintEvent): """ Override default rendering to elide button text if it is bigger than half the window size """ painter = QPainter(self) metrics = painter.fontMetrics() right_element_widths = self.rapidApp.downloadButton.width() + self.rapidApp.menuButton.width() window_width = self.rapidApp.width() window_half = window_width / 2 if right_element_widths > window_half: maximum_width = window_width - right_element_widths else: maximum_width = window_half maximum_width -= self.padding_side - self.top_row_icon_size # account for situations where we might have negative values, i.e., display some # text at least maximum_width = max(30, maximum_width) usable_width = round(0.9 * maximum_width) elided_text = metrics.elidedText(self.non_elided_text, Qt.ElideMiddle, usable_width) super().setText(elided_text) super().paintEvent(event)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 255))) painter.setPen(QPen(Qt.NoPen)) for i in range(6): if (self.counter // 5) % 6 == i: painter.setBrush( QBrush(QColor(127 + (self.counter % 5) * 32, 127, 127))) else: painter.setBrush(QBrush(QColor(127, 127, 127))) painter.drawEllipse( self.width() / 2 + 30 * math.cos(2 * math.pi * i / 6.0) - 10, self.height() / 2 - 15 + 30 * math.sin(2 * math.pi * i / 6.0) - 10, 20, 20) painter.setPen(QPen(QtGui.QColor(0, 0, 0))) painter.setRenderHint(QPainter.TextAntialiasing) painter.setFont(self.font) metrics = painter.fontMetrics() painter.drawText( QPoint(self.width() / 2 - metrics.width(self.text) / 2, self.height() / 2 + 60), self.text) painter.end()
def _paint_regular( self, painter: QtGui.QPainter, option: QtWidgets.QStyleOptionViewItem, text: str, alignment: int, background: QtGui.QColor, ) -> None: if not isinstance(background, QtCore.QVariant): painter.setPen(QtCore.Qt.NoPen) painter.setBrush(QtGui.QBrush(background)) painter.drawRect(option.rect) rect = option.rect metrics = painter.fontMetrics() regex = "({})".format( "|".join(re.escape(sep) for sep in HIGHLIGHTABLE_CHUNKS) ) for chunk in re.split(regex, text): painter.setPen( self._theme_mgr.get_color("grid/ass-mark") if chunk in HIGHLIGHTABLE_CHUNKS else option.palette.color(QtGui.QPalette.Text) ) # chunk = metrics.elidedText( # chunk, QtCore.Qt.ElideRight, rect.width() # ) painter.drawText(rect, alignment, chunk) rect = rect.adjusted(metrics.width(chunk), 0, 0, 0)
def clipText(self, text: str, painter: QPainter, chapter: bool = False) -> str: metrics = painter.fontMetrics() return metrics.elidedText( text, Qt.ElideRight, (self.parent.width() - 10 if chapter else 100 - 10))
def paintEvent(self, evt): QLabel.paintEvent(self, evt) p = QPainter(self) p.setFont(self.font()) x = self._movieWidth + 6 y = (self.height() + p.fontMetrics().xHeight()) / 2 p.drawText(x, y, self._text) p.end()
def paintTab(self, painter: QPainter, index: int): if not self.isValidIndex(index): return painter.save() tab = self._tabs[index] rect = self._tabRect(index) selected = index == self._currentIndex enabled = self._enabled and tab.enabled if selected: painter.fillRect(rect, FancyToolButtonSelectedColor) tabText = tab.text tabTextRect = QRect(rect) drawIcon = rect.height() > 36 tabIconRect = QRect(rect) tabTextRect.translate(0, -2 if drawIcon else 1) boldFont = QFont(painter.font()) boldFont.setPointSizeF(SIDEBAR_FONT_SIZE) boldFont.setBold(True) painter.setFont(boldFont) #painter.setPen(QColor(255, 255, 255, 160) if selected else QColor(0, 0, 0, 110)) textFlags = Qt.AlignCenter | (Qt.AlignBottom if drawIcon else Qt.AlignVCenter) | Qt.TextWordWrap fader = tab.fader if fader > 0 and not selected and enabled: painter.save() painter.setOpacity(fader) painter.fillRect(rect, FancyToolButtonHoverColor) painter.restore() if not enabled: painter.setOpacity(0.7) if drawIcon: textHeight = (painter.fontMetrics().boundingRect( QRect(0, 0, self.width(), self.height()), Qt.TextWordWrap, tabText).height()) tabIconRect.adjust(0, 4, 0, -textHeight - 4) iconMode = (QIcon.Active if selected else QIcon.Normal) if enabled else QIcon.Disabled iconRect = QRect(0, 0, MODEBAR_ICON_SIZE, MODEBAR_ICON_SIZE) iconRect.moveCenter(tabIconRect.center()) iconRect = iconRect.intersected(tabIconRect) drawIconWithShadow(tab.icon, iconRect, painter, iconMode) if enabled: penColor = FancyTabWidgetEnabledSelectedTextColor if selected else FancyTabWidgetEnabledUnselectedTextColor else: penColor = FancyTabWidgetDisabledSelectedTextColor if selected else FancyTabWidgetDisabledUnselectedTextColor painter.setPen(penColor) painter.translate(0, -1) painter.drawText(tabTextRect, textFlags, tabText) painter.restore()
def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ painter = QPainter() painter.begin(printer) # calculate margin and width of printout font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = ( Preferences.getPrinter("LeftMargin") * int(printer.resolution() / 2.54) - marginX ) marginY = printer.pageRect().y() - printer.paperRect().y() marginY = ( Preferences.getPrinter("TopMargin") * int(printer.resolution() / 2.54) - marginY ) width = ( printer.width() - marginX - Preferences.getPrinter("RightMargin") * int(printer.resolution() / 2.54) ) height = ( printer.height() - fontHeight - 4 - marginY - Preferences.getPrinter("BottomMargin") * int(printer.resolution() / 2.54) ) # write a foot note s = self.tr("Diagram: {0}").format(self.getDiagramName()) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) # render the diagram size = self.pixmapLabel.pixmap().size() size.scale(QSize(width - 10, height - 10), # 5 px inner margin Qt.KeepAspectRatio) painter.setViewport(marginX + 5, marginY + 5, size.width(), size.height()) painter.setWindow(self.pixmapLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.pixmapLabel.pixmap()) painter.end()
def paintEvent(self, event): qp = QPainter() qp.begin(self) metrics = qp.fontMetrics() ascent = metrics.ascent() self.max_x = metrics.width(self.text()) if self.max_x > self.width(): qp.drawText(self.x, ascent, self.text()) else: qp.drawText(0, ascent, self.text()) qp.end()
def _draw_scale(self, painter: QtGui.QPainter) -> None: h = painter.viewport().height() one_second = 1000 one_minute = 60 * one_second start_pts = int(self._view.view_start // one_minute) * one_minute end_pts = (int(self._view.view_end + one_minute) // one_minute) * one_minute painter.setPen( QtGui.QPen(self.palette().text(), 1, QtCore.Qt.SolidLine)) painter.setFont(QtGui.QFont(self.font().family(), 8)) text_height = painter.fontMetrics().capHeight() for pts in range(start_pts, end_pts, one_second): x = round(self.pts_to_x(pts)) if x < 0 or x >= self.width(): continue if pts % one_minute == 0: gap = h - 1 else: gap = 4 painter.drawLine(x, 0, x, gap) if pts % one_minute == 0: text = "{:02}:{:02}".format(pts // one_minute, 0) elif pts % (10 * one_second) == 0: long_text = "{:02}:{:02}".format( pts // one_minute, (pts % one_minute) // one_second) long_text_width = painter.fontMetrics().width(long_text) next_label_x = round(self.pts_to_x(pts + 10 * one_second)) if long_text_width < next_label_x - x: text = long_text else: text = "{:02}".format((pts % one_minute) // one_second) else: continue painter.drawText(x + 2, text_height + (h - text_height) / 2, text)
def drawKey(self, painter, cursor, name, x, y): pix = QPixmap(self.height() / 10, self.height() / 20) pix.fill(Qt.transparent) pain = QPainter(pix) pain.setFont(QFont("Times New Roman", self.height() / 40)) metrics = pain.fontMetrics() button_width = max(self.height() / 20, metrics.width(name) + self.height() / 80 + 6) pain.drawText((button_width - metrics.width(name)) / 2, self.height() * 3 / 80 - 3, name) pain.end() rect = QRect(x, y, button_width, self.height() / 20 + 4) self.drawButton(painter, cursor, rect, pix, resize=False) return rect
def paintEvent(self, event): p = QPainter(self) font = QFont() font.setPointSize(12) font.setBold(True) font.setWeight(75) p.setFont(font) p.setPen(Qt.black) p.setBrush(self.player.color) txt_s = p.fontMetrics().width( self.text) + 4, p.fontMetrics().height() + 4 (self.x() + self.width() / 4 - 5, self.y() + self.width() / 4 - 5) xpos = (self.player.x() + self.player.width() / 4 - 5) - txt_s[0] if xpos < 0: xpos = (self.player.x() + 3 * (self.player.width() / 4) + 5) ypos = (self.player.y() + self.height() / 4 - 5) - txt_s[1] + 4 if ypos < 0: ypos = (self.player.y() + self.height() / 4 - 5) + txt_s[1] + 4 if self.pos() != QPoint(xpos, ypos) or self.size() != QSize( txt_s[0] + 4, txt_s[1] + 4): self.move(xpos, ypos) self.resize(txt_s[0] + 4, txt_s[1] + 4) p.end() self.update() return p.drawRoundedRect(0, 0, *txt_s, 4, 4) p.drawText(2, txt_s[1] - 4, self.text) p.end()
def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ painter = QPainter() painter.begin(printer) # calculate margin and width of printout font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = Preferences.getPrinter("LeftMargin") * \ int(printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = Preferences.getPrinter("TopMargin") * \ int(printer.resolution() / 2.54) - marginY width = printer.width() - marginX - \ Preferences.getPrinter("RightMargin") * \ int(printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY - \ Preferences.getPrinter("BottomMargin") * \ int(printer.resolution() / 2.54) # write a foot note s = self.tr("Diagram: {0}").format(self.getDiagramName()) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) # render the diagram size = self.pixmapLabel.pixmap().size() size.scale(QSize(width - 10, height - 10), # 5 px inner margin Qt.KeepAspectRatio) painter.setViewport(marginX + 5, marginY + 5, size.width(), size.height()) painter.setWindow(self.pixmapLabel.pixmap().rect()) painter.drawPixmap(0, 0, self.pixmapLabel.pixmap()) painter.end()
def paintEvent(self, event): painter = QPainter(self) painter.fillRect(self.rect(), Qt.black) if self.pixmap.isNull(): painter.setPen(Qt.white) painter.drawText( self.rect(), Qt.AlignCenter, "Rendering initial image, please wait..." ) return if self.curScale == self.pixmapScale: painter.drawPixmap(self.pixmapOffset, self.pixmap) else: scaleFactor = self.pixmapScale / self.curScale newWidth = int(self.pixmap.width() * scaleFactor) newHeight = int(self.pixmap.height() * scaleFactor) newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2 newY = self.pixmapOffset.y() + (self.pixmap.height() - newHeight) / 2 painter.save() painter.translate(newX, newY) painter.scale(scaleFactor, scaleFactor) exposed, _ = painter.matrix().inverted() exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1) painter.drawPixmap(exposed, self.pixmap, exposed) painter.restore() text = ( "Use mouse wheel or the '+' and '-' keys to zoom. Press and " "hold left mouse button to scroll." ) metrics = painter.fontMetrics() textWidth = metrics.width(text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(0, 0, 0, 127)) painter.drawRect( (self.width() - textWidth) / 2 - 5, 0, textWidth + 10, metrics.lineSpacing() + 5, ) painter.setPen(Qt.white) painter.drawText( (self.width() - textWidth) / 2, metrics.leading() + metrics.ascent(), text )
def getPreview(save): save = BlackAndWhite2SaveGame(save) lines = [ [ (u"Name : " + save.getName(), Qt.AlignLeft), (u"| Profile : " + save.getSaveGroupIdentifier()[1:], Qt.AlignLeft), ], [(u"Land number : " + save.getLand(), Qt.AlignLeft)], [(u"Saved at : " + save.getCreationTime().toString(), Qt.AlignLeft)], [(u"Elapsed time : " + save.getElapsed(), Qt.AlignLeft)], ] pixmap = QPixmap(320, 320) pixmap.fill() # rightBuffer = [] painter = QPainter() painter.begin(pixmap) fm = painter.fontMetrics() margin = 5 height = 0 width = 0 ln = 0 for line in lines: cHeight = 0 cWidth = 0 for (toPrint, align) in line: bRect = fm.boundingRect(toPrint) cHeight = bRect.height() * (ln + 1) bRect.moveTop(cHeight - bRect.height()) if align != Qt.AlignLeft: continue else: bRect.moveLeft(cWidth + margin) cWidth = cWidth + bRect.width() painter.drawText(bRect, align, toPrint) height = max(height, cHeight) width = max(width, cWidth + (2 * margin)) ln = ln + 1 # height = height + lh painter.end() return pixmap.copy(0, 0, width, height)
def paintEvent(self, event): par = self.parent() size = min(self.spinner_size, par.width(), par.height()) dot_count = 5 dot_size = int(size / dot_count) * 1.5 r = par.rect() spinner_rect = QRect(r.width() / 2 - size / 2, r.height() / 2 - size / 2, size, size) painter = QPainter() painter.begin(self) painter.setPen(QPen(Qt.NoPen)) for i in range(dot_count): if self.counter % dot_count == i: painter.setBrush(QBrush(QColor(0, 0, 0))) d_size = dot_size * 1.1 else: painter.setBrush(QBrush(QColor(200, 200, 200))) d_size = dot_size r = size / 2 - dot_size / 2 x = r * math.cos(2 * math.pi * i / dot_count) y = r * math.sin(2 * math.pi * i / dot_count) x_center = spinner_rect.left( ) + spinner_rect.width() / 2 - dot_size / 2 y_center = spinner_rect.top( ) + spinner_rect.height() / 2 - dot_size / 2 painter.drawEllipse(x_center + x, y_center + y, d_size, d_size) if self.message: painter.setPen(QPen(Qt.black)) if self.font_size: f = painter.font() f.setPointSize(self.font_size) painter.setFont(f) spinner_rect.setTop(spinner_rect.bottom() + 3) spinner_rect.setHeight(painter.fontMetrics().height() * 1.5) r = painter.boundingRect(spinner_rect, Qt.AlignHCenter | Qt.AlignTop, self.message) painter.drawText(r.bottomLeft(), self.message) painter.end()
def Print(self, p: QPainter, m: QMargins, o: int = 0): if self.Report.TotalPagesCalculated is False or self.Visible is False: return r1, r2 = self.Report.onBeforePrint( self.Report._CurrentCopys, self.Section, self.Section._GetCurrentPrintRecord(), self) if r1: return txt = r2 if not (r2 is None) else self.getPrintText() rect = self._NewRect(m, o) # 填充颜色 if self.FillColor: p.fillRect(rect, self.FillColor) # 绘制边框及文本 if self.Bolder or self.FillColor: p.drawRect(rect) rect = rect - QMargins(1, 1, 1, 1) p.setFont(self.Font) if self.Transform: # 文本旋转的情况 FontHeight = QFontMetrics(self.Font).height() p.save() p.translate(self.Rect.x() + m.left() + FontHeight, self.Rect.y() + m.top() + o) # 第一个参数为距离 p.rotate(90) p.drawText(QRect(0, 0, self.Rect.width(), self.Rect.height()), self.AlignmentFlag, txt) # 第一个参数Left为调整后距离页面顶端的距离 p.restore() else: # 文字不旋转的情况 fm = p.fontMetrics() # 处理长文本省略 if self.AutoEllipsis: elidedText = fm.elidedText(txt, Qt.ElideRight, rect.width()) # 处理长文本自动缩小字体 if self.AutoShrinkFont: self.__AutoShrinkFont(p, rect, txt) if self.AutoEllipsis: p.drawText(rect, self.AlignmentFlag, elidedText) else: p.drawText(rect, self.AlignmentFlag, txt)
def __print(self, printer): """ Private slot to the actual printing. @param printer reference to the printer object (QPrinter) """ painter = QPainter() painter.begin(printer) # calculate margin and width of printout font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = Preferences.getPrinter("LeftMargin") * \ int(printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = Preferences.getPrinter("TopMargin") * \ int(printer.resolution() / 2.54) - marginY width = printer.width() - marginX - \ Preferences.getPrinter("RightMargin") * \ int(printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY - \ Preferences.getPrinter("BottomMargin") * \ int(printer.resolution() / 2.54) # write a foot note s = self.tr("Diagram: {0}").format(self.getDiagramName()) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) # render the diagram painter.setViewport(marginX, marginY, width, height) self.svgWidget.renderer().render(painter) painter.end()
def paintEvent(self, e): p = QPainter(self) opt = QStyleOptionSlider() self.initStyleOption(opt) p.translate(opt.rect.x(), opt.rect.y()) p.setPen(opt.palette.windowText().color()) # tickOffset = sty.pixelMetric(QStyle.PM_SliderTickmarkOffset, opt, self.slider) available = self.style().pixelMetric(QStyle.PM_SliderSpaceAvailable, opt, self) slen = self.style().pixelMetric(QStyle.PM_SliderLength, opt, self) fudge = slen / 2 for i in range(len(self.labels)): v = opt.minimum + i pos = self.style().sliderPositionFromValue(opt.minimum, opt.maximum, v, available) + fudge # p.drawLine(pos, 0, pos, tickOffset - 2) br = p.fontMetrics().boundingRect(self.labels[i]) pos = min(max(pos, br.width()/2), available+fudge-br.width()/2) p.drawStaticText(pos - br.width()/2, 0, QStaticText(self.labels[i])) super().paintEvent(e)
def paint(self, painter: QPainter, option, widget=None): painter.setPen(QPen(Qt.black, 0)) self.rect = getRect(widget) gradient = QLinearGradient(self.rect.topLeft(), self.rect.bottomLeft()) gradient.setColorAt(0, Qt.red) gradient.setColorAt(1, Qt.green) painter.setBrush(gradient) painter.drawRect(self.rect) metrics = painter.fontMetrics() for level in self.levels: text = str(int(level)) w, h = metrics.width(text), metrics.height() y = self.rect.height() - (level - self.start) / ( self.end - self.start) * self.rect.height() + self.rect.y() - h / 2 x = self.rect.x() - w - 10 text_rect = QRectF(x, y, w, h) painter.drawText(text_rect, Qt.AlignRight, text)
def paintEvent(self, event): p = QPainter(self) # Need this configuration to enable stylesheets for subclasses of QWidgets opt = QStyleOption() opt.initFrom(self) self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self) # Set font font = QFont(p.font()) font.setFamily("Helvetica Neue") p.setFont(font) actionY = 0 for action in self.actionList: actionRect = QRect(0, actionY, self.actionWidth, self.actionHeight) if action.isChecked(): p.fillRect(actionRect, QColor(35, 35, 35)) #if action == mOverAction: # p.fillRect(actionRect, QColor(150, 150, 150)) # Draw text for button p.setPen(QColor(255, 255, 255)) size = p.fontMetrics().size(Qt.TextSingleLine, action.text()) actionTextRect = QRect( QPoint(actionRect.width() / 2 - size.width() / 2, actionRect.bottom() - size.height() - 5), size) p.drawText(actionTextRect, Qt.AlignCenter, action.text()) # Draw button actionIconRect = QRect( 0, actionY, actionRect.width(), actionRect.height() - 2 * actionTextRect.height() - 10) actionIcon = QIcon(action.icon()) actionIcon.paint(p, actionIconRect) # Move to next button location actionY += actionRect.height()
def run(self): painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) life_time_seconds = self.life_time_seconds while life_time_seconds > 0: life_time_seconds -= 1 text = seconds_to_str(life_time_seconds) img = QImage(320, 240, QImage.Format_ARGB32) img.fill(Qt.white) painter.begin(img) # Рисование рамки вокруг картинки border_rect = img.rect() border_rect.setWidth(border_rect.width() - 1) border_rect.setHeight(border_rect.height() - 1) painter.drawRect(border_rect) try: # Алгоритм изменения размера текста взят из http://stackoverflow.com/a/2204501 # Для текущего пришлось немного адаптировать factor = img.width() / painter.fontMetrics().width( text) / 1.5 # Ширина текста 2/3 от ширины if factor < 1 or factor > 1.25: f = painter.font() point_size = f.pointSizeF() * factor if point_size > 0: f.setPointSizeF(point_size) painter.setFont(f) painter.drawText(img.rect(), Qt.AlignCenter, text) finally: painter.end() self.new_img.emit(img.copy()) time.sleep(1)
def paint(self, painter: QtGui.QPainter, options, widget=None): painter.drawPixmap(self._zero_point, self._pixmap) if self._highlight is not None: painter.setBrush(QtGui.QBrush(self._highlight)) painter.setPen(QtCore.Qt.NoPen) painter.drawRect(self._bounding_rect) painter.setBrush(QtGui.QBrush()) if self._info_text is not None: painter.setFont(QtGui.QFont('Helvetica', 32)) painter.setBrush(QtGui.QBrush(QtGui.QColor(230, 230, 230, 180))) painter.setPen(QtCore.Qt.NoPen) text_rect = painter.fontMetrics().boundingRect(self._info_text) top_corner = self._bounding_rect.adjusted(self.INFO_TEXT_X_OFFSET, self.INFO_TEXT_Y_OFFSET, 0, 0).topLeft() painter.drawRect( text_rect.adjusted(self.INFO_TEXT_X_OFFSET, self.INFO_TEXT_Y_OFFSET, self.INFO_TEXT_X_OFFSET, self.INFO_TEXT_Y_OFFSET)) painter.setPen(QtGui.QPen(QtGui.QColor(10, 10, 10, 230))) painter.drawText(top_corner, self._info_text) if self.isSelected(): pen_width = math.ceil( self._selection_highlight_pen.width() / 2) - 1 painter.setBrush(QtCore.Qt.NoBrush) painter.setPen(self._selection_highlight_pen) painter.drawRect(self.boundingRect().adjusted( pen_width, pen_width, -pen_width, -pen_width, ))
def paintEvent(self, e: QPaintEvent) -> None: if (self.model() and self.model().rowCount()) \ or not (self.emptyViewMsg or self.emptyViewIcon): super(BasicTreeView, self).paintEvent(e) else: # If no items draw a text in the center of the viewport. position = self.viewport().rect().center() if self.emptyViewMsg: painter = QPainter(self.viewport()) textRect = painter.fontMetrics().boundingRect( self.emptyViewMsg) textRect.moveCenter(position) painter.drawText(textRect, Qt.AlignCenter, self.emptyViewMsg) # set position for icon position.setY(position.y() + textRect.height() + 25) if self.emptyViewIcon: iconRect = QRect(0, 0, 50, 50) iconRect.moveCenter(position) painter.drawPixmap(iconRect, self.emptyViewIcon.pixmap(QSize(50, 50)))
def draw_annotation_text(annotation: dict, image: QImage, painter: QPainter): # d'abord font params font = painter.font() style = annotation["style"] font.setPixelSize( image.height() / ( style["pointSize"] or KEEP_UPDATED_CONFIGURATION["annotationCurrentTextSizeFactor"] ) ) font.setUnderline(style["underline"]) # get considère empty "" comme true if not style.get("family", None): # pragma: no branch font_name = DTB().getConfig("fontMain") font.setFamily(font_name) # pragma: no cover painter.setFont(font) # Ensuite le crayon pen = painter.pen() pen.setColor(style["fgColor"]) painter.setPen(pen) # On evalue la taille de et la position de l'annotation size = painter.fontMetrics().size(0, annotation["text"]) rect = QRectF( QPoint(annotation["x"] * image.width(), annotation["y"] * image.height()), QSizeF(size), ) # painter.setOpacity(ANNOTATION_TEXT_BG_OPACITY) painter.fillRect(rect, style["bgColor"]) painter.setOpacity(1) painter.drawText( rect, annotation["text"], )
def paintEvent(self, event): painter = QPainter(self) painter.fillRect(self.rect(), Qt.black) if self.pixmap.isNull(): painter.setPen(Qt.white) painter.drawText(self.rect(), Qt.AlignCenter, "Rendering initial image, please wait...") return if self.curScale == self.pixmapScale: painter.drawPixmap(self.pixmapOffset, self.pixmap) else: scaleFactor = self.pixmapScale / self.curScale newWidth = int(self.pixmap.width() * scaleFactor) newHeight = int(self.pixmap.height() * scaleFactor) newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2 newY = self.pixmapOffset.y() + (self.pixmap.height() - newHeight) / 2 painter.save() painter.translate(newX, newY) painter.scale(scaleFactor, scaleFactor) exposed, _ = painter.matrix().inverted() exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1) painter.drawPixmap(exposed, self.pixmap, exposed) painter.restore() text = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \ "hold left mouse button to scroll." metrics = painter.fontMetrics() textWidth = metrics.width(text) painter.setPen(Qt.NoPen) painter.setBrush(QColor(0, 0, 0, 127)) painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10, metrics.lineSpacing() + 5) painter.setPen(Qt.white) painter.drawText((self.width() - textWidth) / 2, metrics.leading() + metrics.ascent(), text)
def _paintSoundLevel(self, painter: QPainter) -> None: """Paint wave (power) """ fontMetrics = painter.fontMetrics() pen = painter.pen() width = self.width() height = self.height() text_height = fontMetrics.height() # write times pen.setColor(Qt.black) start_string = time_str(self._view[0]) end_string = time_str(self._view[1]) painter.drawText(0, height, start_string) painter.drawText(width - fontMetrics.width(end_string), height, end_string) # draw sound wave if self._path is not None: painter.drawPath(self._path) # draw position indicator if self._player is not None: position = self._player.position if position is not None: x_position = int(((position - self._view[0]) / (self._view[1] - self._view[0])) * width) if 0 <= x_position <= width: # draw vertical line painter.setPen(QPen(Qt.red, 1)) painter.drawLine(x_position, 0, x_position, height) # write time position_string = time_str(self._player.position) text_width = fontMetrics.width(position_string) x_location = max( 0, min(x_position - text_width // 2, width - text_width)) painter.drawText(x_location, text_height, position_string)
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget=None): color = self.color if option.state & QStyle.State_Sunken: color = color.darker(200) elif option.state & QStyle.State_MouseOver: color = color.lighter(150) painter.setBrush(color) painter.setPen(QPen(Qt.black, 0)) painter.drawEllipse(self.size) if self.label: text_color = get_foreground_color(color) factor = (self.size.width() - 2) \ / painter.fontMetrics().width(self.label) font = painter.font() if len(self.label) == 1: factor *= 0.5 font.setPointSizeF(font.pointSizeF() * factor) painter.setFont(font) painter.setPen(QPen(text_color, 0)) painter.drawText(self.size, Qt.AlignHCenter | Qt.AlignVCenter, self.label)
def printDiagram(self, printer, diagramName=""): """ Public method to print the diagram. @param printer reference to a ready configured printer object (QPrinter) @param diagramName name of the diagram (string) """ painter = QPainter() painter.begin(printer) offsetX = 0 offsetY = 0 widthX = 0 heightY = 0 font = QFont("times", 10) painter.setFont(font) fm = painter.fontMetrics() fontHeight = fm.lineSpacing() marginX = printer.pageRect().x() - printer.paperRect().x() marginX = \ Preferences.getPrinter("LeftMargin") * int( printer.resolution() / 2.54) - marginX marginY = printer.pageRect().y() - printer.paperRect().y() marginY = \ Preferences.getPrinter("TopMargin") * int( printer.resolution() / 2.54) - marginY width = printer.width() - marginX \ - Preferences.getPrinter("RightMargin") * int( printer.resolution() / 2.54) height = printer.height() - fontHeight - 4 - marginY \ - Preferences.getPrinter("BottomMargin") * int( printer.resolution() / 2.54) border = self.border == 0 and 5 or self.border rect = self._getDiagramRect(border) diagram = self.__getDiagram(rect) finishX = False finishY = False page = 0 pageX = 0 pageY = 1 while not finishX or not finishY: if not finishX: offsetX = pageX * width pageX += 1 elif not finishY: offsetY = pageY * height offsetX = 0 pageY += 1 finishX = False pageX = 1 if (width + offsetX) > diagram.width(): finishX = True widthX = diagram.width() - offsetX else: widthX = width if diagram.width() < width: widthX = diagram.width() finishX = True offsetX = 0 if (height + offsetY) > diagram.height(): finishY = True heightY = diagram.height() - offsetY else: heightY = height if diagram.height() < height: finishY = True heightY = diagram.height() offsetY = 0 painter.drawPixmap(marginX, marginY, diagram, offsetX, offsetY, widthX, heightY) # write a foot note s = self.tr("{0}, Page {1}").format(diagramName, page + 1) tc = QColor(50, 50, 50) painter.setPen(tc) painter.drawRect(marginX, marginY, width, height) painter.drawLine(marginX, marginY + height + 2, marginX + width, marginY + height + 2) painter.setFont(font) painter.drawText(marginX, marginY + height + 4, width, fontHeight, Qt.AlignRight, s) if not finishX or not finishY: printer.newPage() page += 1 painter.end()
def paintEvent(self, e): # Three valid cases: there are both a goal and current framerate # or either of them if self.fps is not None: if self.g_fps is not None: lb = min(self.fps_inertia_min, self.g_fps) ub = max(self.fps_inertia_max, self.g_fps) else: lb = self.fps_inertia_min ub = self.fps_inertia_max else: if self.g_fps is not None: lb = self.g_fps ub = self.g_fps else: return min_bound = np.floor(lb * 0.08) * 10 max_bound = np.ceil(ub * 0.12) * 10 delta_bound = max_bound - min_bound size = self.size() pad = 6 w = size.width() h = size.height() p = QPainter() p.begin(self) fm = p.fontMetrics() if max_bound == min_bound: max_bound += 1 limit_color = (200, 200, 200) goal_color = (80, 80, 80) if self.fps is not None and self.g_fps is not None and self.fps < self.g_fps: indicator_color = self.error_indicator_color shadow_color = self.error_indicator_shadow_color else: indicator_color = self.indicator_color shadow_color = self.indicator_shadow_color w_min = 0 w_max = w - pad delta_w = w_max - w_min text_height = 16 h_max = h - pad h_min = text_height + pad if self.set_fps and self.fps is not None: loc = (self.fps - min_bound) / delta_bound w_l = int(w_min + loc * delta_w) w_shadow_min = int( w_min + (self.fps_inertia_min - min_bound) * delta_w / delta_bound ) w_shadow_max = int( w_min + (self.fps_inertia_max - min_bound) * delta_w / delta_bound ) # Draw the inertially moving rectangle p.setPen(Qt.NoPen) p.setBrush(QBrush(QColor(*shadow_color))) l_corner = w_shadow_min w_rect = w_shadow_max - w_shadow_min p.drawRect(l_corner, h_min, w_rect, h_max - h_min) # Draw the indicator line p.setPen(QPen(QColor(*indicator_color))) p.drawLine(w_l, h_min, w_l, h_max + 5) val_str = "{:.1f}".format(self.fps) textw = fm.width(val_str) p.drawText(QPoint((w_max + w_min - textw) // 2, text_height), val_str) if self.g_fps is not None: # Draw the goal line loc_g = (self.g_fps - min_bound) / delta_bound p.setPen(QPen(QColor(*goal_color), 3)) w_l = int(w_min + loc_g * delta_w) p.drawLine(w_l, h_min, w_l, h_max) # Draw the limits p.setPen(QPen(QColor(*limit_color))) p.drawLine(w_min, h_min, w_min, h_max) p.drawLine(w_max, h_min, w_max, h_max) p.drawText(QPoint(w_min, text_height), str(min_bound)) maxst = str(max_bound) textw = fm.width(maxst) p.drawText(QPoint(w_max - textw, text_height), maxst) p.end()
def paintEvent(self, _event: QPaintEvent): if not self.crop or not self.resolution: return painter = QPainter(self) # Keep a backup of the transform and create a new one transform = painter.worldTransform() # Set scaling transform transform = transform.scale(self.width() / self.resolution.width(), self.height() / self.resolution.height()) # Compute the transform to flip the coordinate system on the x axis transform_flip = QTransform() if self.flip_x: transform_flip = transform_flip.translate(self.resolution.width(), 0.0) transform_flip = transform_flip.scale(-1.0, 1.0) # Small helper for tuple to QPoint def toqp(point): return QPoint(point[0], point[1]) # Starting from here we care about AA painter.setRenderHint(QPainter.Antialiasing) # Draw all the QR code results for res in self.results: painter.setWorldTransform(transform_flip * transform, False) # Draw lines between all of the QR code points pen = QPen(self.qr_outline_pen) if res in self.validator_results.result_colors: pen.setColor(self.validator_results.result_colors[res]) painter.setPen(pen) num_points = len(res.points) for i in range(0, num_points): i_n = i + 1 line_from = toqp(res.points[i]) line_from += self.crop.topLeft() line_to = toqp( res.points[i_n] if i_n < num_points else res.points[0]) line_to += self.crop.topLeft() painter.drawLine(line_from, line_to) # Draw the QR code data # Note that we reset the world transform to only the scaled transform # because otherwise the text could be flipped. We only use transform_flip # to map the center point of the result. painter.setWorldTransform(transform, False) font_metrics = painter.fontMetrics() data_metrics = QSize(font_metrics.horizontalAdvance(res.data), font_metrics.capHeight()) center_pos = toqp(res.center) center_pos += self.crop.topLeft() center_pos = transform_flip.map(center_pos) text_offset = QPoint(data_metrics.width(), data_metrics.height()) text_offset = text_offset / 2 text_offset.setX(-text_offset.x()) center_pos += text_offset padding = self.BG_RECT_PADDING bg_rect_pos = center_pos - QPoint(padding, data_metrics.height() + padding) bg_rect_size = data_metrics + (QSize(padding, padding) * 2) bg_rect = QRect(bg_rect_pos, bg_rect_size) bg_rect_path = QPainterPath() radius = self.BG_RECT_CORNER_RADIUS bg_rect_path.addRoundedRect(QRectF(bg_rect), radius, radius, Qt.AbsoluteSize) painter.setPen(self.bg_rect_pen) painter.fillPath(bg_rect_path, self.bg_rect_fill) painter.drawPath(bg_rect_path) painter.setPen(self.text_pen) painter.drawText(center_pos, res.data)