def paint_detail_view(self, painter: QPainter) -> None: self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height()) self.paint_thumbnail(painter) lst = ([self.fileinfo.basename(), bytefmt.humanize(self.fileinfo.size())] + list(self.make_text())) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) total_width = self.tile_rect.width() - self.thumbnail_rect.width() - 8 widths = [60, 10, 10, 10, 10, 10] x = self.thumbnail_rect.width() + 4 for idx, text in enumerate(lst[:-1]): if idx != 0: text_option.setAlignment(Qt.AlignRight | Qt.AlignVCenter) width = total_width * (widths[idx] / 100) painter.drawText(QRectF(x, 0, width, self.tile_rect.height()), text, text_option) x += width
def paint_detail_view(self, painter: QPainter) -> None: self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height()) self.paint_thumbnail(painter) lst = ( [self.fileinfo.basename(), bytefmt.humanize(self.fileinfo.size())] + list(self.make_text())) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) total_width = self.tile_rect.width() - self.thumbnail_rect.width() - 8 widths = [60, 10, 10, 10, 10, 10] x = self.thumbnail_rect.width() + 4 for idx, text in enumerate(lst[:-1]): if idx != 0: text_option.setAlignment(Qt.AlignRight | Qt.AlignVCenter) width = total_width * (widths[idx] / 100) painter.drawText(QRectF(x, 0, width, self.tile_rect.height()), text, text_option) x += width
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment(QStyle.visualAlignment( self._opt.direction, self._opt.displayAlignment)) if self._doc is not None: self._doc.deleteLater() self._doc = QTextDocument(self) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDocumentMargin(2) stylesheet = """ .highlight { color: {{ conf.colors.completion.match.fg }}; } """ with jinja.environment.no_autoescape(): template = jinja.environment.from_string(stylesheet) self._doc.setDefaultStyleSheet(template.render(conf=config.val)) if index.parent().isValid(): view = self.parent() pattern = view.pattern columns_to_filter = index.model().columns_to_filter(index) if index.column() in columns_to_filter and pattern: repl = r'<span class="highlight">\g<0></span>' text = re.sub(re.escape(pattern).replace(r'\ ', r'|'), repl, self._opt.text, flags=re.IGNORECASE) self._doc.setHtml(text) else: self._doc.setPlainText(self._opt.text) else: self._doc.setHtml( '<span style="font: {};">{}</span>'.format( html.escape(config.val.fonts.completion.category), html.escape(self._opt.text)))
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ if self._opt is None: raise AssertionError # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment( QStyle.visualAlignment(self._opt.direction, self._opt.displayAlignment)) if self._doc is not None: self._doc.deleteLater() self._doc = QTextDocument(self) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDocumentMargin(2) if index.parent().isValid(): view = self.parent() pattern = view.pattern columns_to_filter = index.model().columns_to_filter(index) if index.column() in columns_to_filter and pattern: pat = re.escape(pattern).replace(r'\ ', r'|') if self._opt.state & QStyle.State_Selected: color = config.val.colors.completion.item.selected.match.fg else: color = config.val.colors.completion.match.fg _Highlighter(self._doc, pat, color) self._doc.setPlainText(self._opt.text) else: self._doc.setHtml('<span style="font: {};">{}</span>'.format( html.escape(config.val.fonts.completion.category), html.escape(self._opt.text)))
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/The-Compiler/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment( QStyle.visualAlignment(self._opt.direction, self._opt.displayAlignment)) self._doc = QTextDocument(self) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDefaultStyleSheet( style.get_stylesheet(""" .highlight { color: {{ color['completion.match.fg'] }}; } """)) self._doc.setDocumentMargin(2) if index.parent().isValid(): pattern = index.model().pattern columns_to_filter = index.model().srcmodel.columns_to_filter if index.column() in columns_to_filter and pattern: repl = r'<span class="highlight">\g<0></span>' text = re.sub(re.escape(pattern), repl, self._opt.text, flags=re.IGNORECASE) self._doc.setHtml(text) else: self._doc.setPlainText(self._opt.text) else: self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment(QStyle.visualAlignment( self._opt.direction, self._opt.displayAlignment)) self._doc = QTextDocument(self) if index.parent().isValid(): self._doc.setPlainText(self._opt.text) else: self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text))) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDefaultStyleSheet(style.get_stylesheet(""" .highlight { {{ color['completion.match.fg'] }} } """)) self._doc.setDocumentMargin(2) if index.column() == 0: marks = index.data(basecompletion.Role.marks) if marks is None: return for mark in marks: cur = QTextCursor(self._doc) cur.setPosition(mark[0]) cur.setPosition(mark[1], QTextCursor.KeepAnchor) txt = cur.selectedText() cur.removeSelectedText() cur.insertHtml('<span class="highlight">{}</span>'.format( html.escape(txt)))
def sizeHint(self, option, index): msg = index.model().data(index, Qt.DisplayRole) field = QRect(option.rect) field.setWidth(variables.window_width - variables.WINDOW_PADDING) field = field.marginsRemoved(variables.TEXT_PADDING) doc = QTextDocument(msg.text) doc.setDocumentMargin(0) opt = QTextOption() opt.setWrapMode(opt.WrapAtWordBoundaryOrAnywhere) doc.setDefaultTextOption(opt) doc.setDefaultFont(variables.font) if msg.user == variables.USER_ME: doc.setTextWidth(field.size().width() - 20 - 50) else: doc.setTextWidth(field.size().width() - 20) field.setHeight(int(doc.size().height())) field.setWidth(int(doc.idealWidth())) field = field.marginsAdded(variables.TEXT_PADDING) return QSize(0, field.size().height())
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/The-Compiler/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment(QStyle.visualAlignment( self._opt.direction, self._opt.displayAlignment)) if self._doc is not None: self._doc.deleteLater() self._doc = QTextDocument(self) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDefaultStyleSheet(style.get_stylesheet(""" .highlight { color: {{ color['completion.match.fg'] }}; } """)) self._doc.setDocumentMargin(2) if index.parent().isValid(): pattern = index.model().pattern columns_to_filter = index.model().srcmodel.columns_to_filter if index.column() in columns_to_filter and pattern: repl = r'<span class="highlight">\g<0></span>' text = re.sub(re.escape(pattern).replace(r'\ ', r'.*'), repl, self._opt.text, flags=re.IGNORECASE) self._doc.setHtml(text) else: self._doc.setPlainText(self._opt.text) else: self._doc.setHtml('<b>{}</b>'.format(html.escape(self._opt.text)))
def _get_textdoc(self, index): """Create the QTextDocument of an item. Args: index: The QModelIndex of the item to draw. """ # FIXME we probably should do eliding here. See # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() if self._opt.features & QStyleOptionViewItem.WrapText: text_option.setWrapMode(QTextOption.WordWrap) else: text_option.setWrapMode(QTextOption.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment(QStyle.visualAlignment( self._opt.direction, self._opt.displayAlignment)) if self._doc is not None: self._doc.deleteLater() self._doc = QTextDocument(self) self._doc.setDefaultFont(self._opt.font) self._doc.setDefaultTextOption(text_option) self._doc.setDocumentMargin(2) if index.parent().isValid(): view = self.parent() pattern = view.pattern columns_to_filter = index.model().columns_to_filter(index) if index.column() in columns_to_filter and pattern: pat = re.escape(pattern).replace(r'\ ', r'|') if self._opt.state & QStyle.State_Selected: color = config.val.colors.completion.item.selected.match.fg else: color = config.val.colors.completion.match.fg _Highlighter(self._doc, pat, color) self._doc.setPlainText(self._opt.text) else: self._doc.setHtml( '<span style="font: {};">{}</span>'.format( html.escape(config.val.fonts.completion.category), html.escape(self._opt.text)))
def text_layout(self, text, width, font, font_metrics): "Lays out wrapped text" text_option = QTextOption(Qt.AlignCenter) text_option.setUseDesignMetrics(True) text_option.setWrapMode(QTextOption.WordWrap) layout = QTextLayout(text, font) layout.setTextOption(text_option) leading = font_metrics.leading() height = 0 layout.setCacheEnabled(True) layout.beginLayout() while True: line = layout.createLine() if not line.isValid(): break line.setLineWidth(width) height += leading line.setPosition(QPointF(0, height)) height += line.height() layout.endLayout() return layout
def printViaQPainter(self): dialog = QPrintDialog(self.printer, self) if not dialog.exec_(): return LeftMargin = 72 sansFont = QFont("Helvetica", 10) sansLineHeight = QFontMetrics(sansFont).height() serifFont = QFont("Times", 11) fm = QFontMetrics(serifFont) DateWidth = fm.width(" September 99, 2999 ") CreditWidth = fm.width(" Credit ") AmountWidth = fm.width(" W999999.99 ") serifLineHeight = fm.height() logo = QPixmap(":/logo.png") painter = QPainter(self.printer) pageRect = self.printer.pageRect() page = 1 for statement in self.statements: painter.save() y = 0 x = pageRect.width() - logo.width() - LeftMargin painter.drawPixmap(x, 0, logo) y += logo.height() + sansLineHeight painter.setFont(sansFont) painter.drawText(x, y, "Greasy Hands Ltd.") y += sansLineHeight painter.drawText(x, y, "New Lombard Street") y += sansLineHeight painter.drawText(x, y, "London") y += sansLineHeight painter.drawText(x, y, "WC13 4PX") y += sansLineHeight painter.drawText(x, y, QDate.currentDate().toString(DATE_FORMAT)) y += sansLineHeight painter.setFont(serifFont) x = LeftMargin for line in statement.address.split(", "): painter.drawText(x, y, line) y += serifLineHeight y += serifLineHeight painter.drawText(x, y, "Dear {0},".format(statement.contact)) y += serifLineHeight balance = statement.balance() painter.drawText( x, y, "The balance of your account is $ {0:,.2f}".format( float(balance))) y += serifLineHeight if balance < 0: painter.setPen(Qt.red) text = "Please remit the amount owing immediately." else: text = ("We are delighted to have done business " "with you.") painter.drawText(x, y, text) painter.setPen(Qt.black) y += int(serifLineHeight * 1.5) painter.drawText(x, y, "Transactions:") y += serifLineHeight option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) for date, amount in statement.transactions: x = LeftMargin h = int(fm.height() * 1.3) painter.drawRect(x, y, DateWidth, h) painter.drawText(QRectF(x + 3, y + 3, DateWidth - 6, h - 6), date.toString(DATE_FORMAT), option) x += DateWidth painter.drawRect(x, y, CreditWidth, h) text = "Credit" if amount < 0: text = "Debit" painter.drawText(QRectF(x + 3, y + 3, CreditWidth - 6, h - 6), text, option) x += CreditWidth painter.drawRect(x, y, AmountWidth, h) if amount < 0: painter.setPen(Qt.red) painter.drawText(QRectF(x + 3, y + 3, AmountWidth - 6, h - 6), "$ {0:,.2f}".format(float(amount)), option) painter.setPen(Qt.black) y += h y += serifLineHeight x = LeftMargin painter.drawText(x, y, "We hope to continue doing " "business with you,") y += serifLineHeight painter.drawText(x, y, "Yours sincerely") y += serifLineHeight * 3 painter.drawText(x, y, "K. Longrey, Manager") x = LeftMargin y = pageRect.height() - 72 painter.drawLine(x, y, pageRect.width() - LeftMargin, y) y += 2 font = QFont("Helvetica", 9) font.setItalic(True) painter.setFont(font) option = QTextOption(Qt.AlignCenter) option.setWrapMode(QTextOption.WordWrap) painter.drawText( QRectF(x, y, pageRect.width() - 2 * LeftMargin, 31), "The contents of this letter are for information " "only and do not form part of any contract.", option) page += 1 if page <= len(self.statements): self.printer.newPage() painter.restore()
def paint(self, painter, option, index): assert isinstance(painter, QPainter) if index.data(Qt.UserRole+1): if app_constants.HIGH_QUALITY_THUMBS: painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setRenderHint(QPainter.Antialiasing) gallery = index.data(Qt.UserRole+1) title = gallery.title artist = gallery.artist title_color = app_constants.GRID_VIEW_TITLE_COLOR artist_color = app_constants.GRID_VIEW_ARTIST_COLOR label_color = app_constants.GRID_VIEW_LABEL_COLOR # Enable this to see the defining box #painter.drawRect(option.rect) # define font size if 20 > len(title) > 15: title_size = "font-size:{}px;".format(self.font_size) elif 30 > len(title) > 20: title_size = "font-size:{}px;".format(self.font_size-1) elif 40 > len(title) >= 30: title_size = "font-size:{}px;".format(self.font_size-2) elif 50 > len(title) >= 40: title_size = "font-size:{}px;".format(self.font_size-3) elif len(title) >= 50: title_size = "font-size:{}px;".format(self.font_size-4) else: title_size = "font-size:{}px;".format(self.font_size) if 30 > len(artist) > 20: artist_size = "font-size:{}px;".format(self.font_size) elif 40 > len(artist) >= 30: artist_size = "font-size:{}px;".format(self.font_size-1) elif len(artist) >= 40: artist_size = "font-size:{}px;".format(self.font_size-2) else: artist_size = "font-size:{}px;".format(self.font_size) #painter.setPen(QPen(Qt.NoPen)) #option.rect = option.rect.adjusted(11, 10, 0, 0) option.rect.setWidth(self.W) option.rect.setHeight(self.H) rec = option.rect.getRect() x = rec[0] y = rec[1] w = rec[2] h = rec[3] text_area = QTextDocument() text_area.setDefaultFont(option.font) text_area.setHtml(""" <head> <style> #area {{ display:flex; width:{6}px; height:{7}px }} #title {{ position:absolute; color: {4}; font-weight:bold; {0} }} #artist {{ position:absolute; color: {5}; top:20px; right:0; {1} }} </style> </head> <body> <div id="area"> <center> <div id="title">{2} </div> <div id="artist">{3} </div> </div> </center> </body> """.format(title_size, artist_size, title, artist, title_color, artist_color, 130+app_constants.SIZE_FACTOR, 1+app_constants.SIZE_FACTOR)) text_area.setTextWidth(w) #chapter_area = QTextDocument() #chapter_area.setDefaultFont(option.font) #chapter_area.setHtml(""" #<font color="black">{}</font> #""".format("chapter")) #chapter_area.setTextWidth(w) def center_img(width): new_x = x if width < w: diff = w - width offset = diff//2 new_x += offset return new_x def img_too_big(start_x): txt_layout = misc.text_layout("Image is too big!", w, self.title_font, self.title_font_m) clipping = QRectF(x, y+h//4, w, app_constants.GRIDBOX_LBL_H - 10) txt_layout.draw(painter, QPointF(x, y+h//4), clip=clipping) # if we can't find a cached image pix_cache = QPixmapCache.find(self.key(gallery.profile)) if isinstance(pix_cache, QPixmap): self.image = pix_cache img_x = center_img(self.image.width()) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) else: self.image = QPixmap(gallery.profile) img_x = center_img(self.image.width()) QPixmapCache.insert(self.key(gallery.profile), self.image) if self.image.width() > w or self.image.height() > h: img_too_big(img_x) else: if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) # draw ribbon type painter.save() painter.setPen(Qt.NoPen) if app_constants.DISPLAY_GALLERY_RIBBON: type_ribbon_w = type_ribbon_l = w*0.11 rib_top_1 = QPointF(x+w-type_ribbon_l-type_ribbon_w, y) rib_top_2 = QPointF(x+w-type_ribbon_l, y) rib_side_1 = QPointF(x+w, y+type_ribbon_l) rib_side_2 = QPointF(x+w, y+type_ribbon_l+type_ribbon_w) ribbon_polygon = QPolygonF([rib_top_1, rib_top_2, rib_side_1, rib_side_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.setBrush(QBrush(QColor(self._ribbon_color(gallery.type)))) painter.drawPath(ribbon_path) # draw if favourited if gallery.fav == 1: star_ribbon_w = star_ribbon_l = w*0.08 rib_top_1 = QPointF(x+star_ribbon_l, y) rib_side_1 = QPointF(x, y+star_ribbon_l) rib_top_2 = QPointF(x+star_ribbon_l+star_ribbon_w, y) rib_side_2 = QPointF(x, y+star_ribbon_l+star_ribbon_w) rib_star_mid_1 = QPointF((rib_top_1.x()+rib_side_1.x())/2, (rib_top_1.y()+rib_side_1.y())/2) rib_star_factor = star_ribbon_l/4 rib_star_p1_1 = rib_star_mid_1 + QPointF(rib_star_factor, -rib_star_factor) rib_star_p1_2 = rib_star_p1_1 + QPointF(-rib_star_factor, -rib_star_factor) rib_star_p1_3 = rib_star_mid_1 + QPointF(-rib_star_factor, rib_star_factor) rib_star_p1_4 = rib_star_p1_3 + QPointF(-rib_star_factor, -rib_star_factor) crown_1 = QPolygonF([rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3]) painter.setBrush(QBrush(QColor("yellow"))) painter.drawPolygon(crown_1) ribbon_polygon = QPolygonF([rib_top_1, rib_side_1, rib_side_2, rib_top_2]) ribbon_path = QPainterPath() ribbon_path.setFillRule(Qt.WindingFill) ribbon_path.addPolygon(ribbon_polygon) ribbon_path.closeSubpath() painter.drawPath(ribbon_path) #painter.setPen(QColor("#d35400")) #painter.drawPolyline(rib_top_1, rib_star_p1_1, rib_star_p1_2, rib_star_mid_1, rib_star_p1_4, rib_star_p1_3, rib_side_1) #painter.drawLine(rib_top_1, rib_top_2) #painter.drawLine(rib_top_2, rib_side_2) #painter.drawLine(rib_side_1, rib_side_2) painter.restore() if app_constants._REFRESH_EXTERNAL_VIEWER: if app_constants.USE_EXTERNAL_VIEWER: self.external_icon = self.file_icons.get_external_file_icon() else: self.external_icon = self.file_icons.get_default_file_icon() if gallery.state == self.G_DOWNLOAD: painter.save() dl_box = QRect(x, y, w, 20) painter.setBrush(QBrush(QColor(0,0,0,123))) painter.setPen(QColor('white')) painter.drawRect(dl_box) painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...') painter.restore() else: if app_constants.DISPLAY_GALLERY_TYPE: self.type_icon = self.file_icons.get_file_icon(gallery.path) if self.type_icon and not self.type_icon.isNull(): self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16)) if app_constants.USE_EXTERNAL_PROG_ICO: if self.external_icon and not self.external_icon.isNull(): self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28)) def draw_text_label(lbl_h): #draw the label for text painter.save() painter.translate(x, y+app_constants.THUMB_H_SIZE) box_color = QBrush(QColor(label_color))#QColor(0,0,0,123)) painter.setBrush(box_color) rect = QRect(0, 0, w, lbl_h) #x, y, width, height painter.fillRect(rect, box_color) painter.restore() return rect if option.state & QStyle.State_MouseOver or\ option.state & QStyle.State_Selected: title_layout = misc.text_layout(title, w, self.title_font, self.title_font_m) artist_layout = misc.text_layout(artist, w, self.artist_font, self.artist_font_m) t_h = title_layout.boundingRect().height() a_h = artist_layout.boundingRect().height() if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H)) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10) painter.setPen(QColor(title_color)) title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE), clip=clipping) painter.setPen(QColor(artist_color)) artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h), clip=clipping) #painter.fillRect(option.rect, QColor) else: if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(self.text_label_h) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) # draw text painter.save() alignment = QTextOption(Qt.AlignCenter) alignment.setUseDesignMetrics(True) title_rect = QRectF(0,0,w, self.title_font_m.height()) artist_rect = QRectF(0,self.artist_font_m.height(),w, self.artist_font_m.height()) painter.translate(x, y+app_constants.THUMB_H_SIZE) if app_constants.GALLERY_FONT_ELIDE: painter.setFont(self.title_font) painter.setPen(QColor(title_color)) painter.drawText(title_rect, self.title_font_m.elidedText(title, Qt.ElideRight, w-10), alignment) painter.setPen(QColor(artist_color)) painter.setFont(self.artist_font) alignment.setWrapMode(QTextOption.NoWrap) painter.drawText(artist_rect, self.title_font_m.elidedText(artist, Qt.ElideRight, w-10), alignment) else: text_area.setDefaultFont(QFont(self.font_name)) text_area.drawContents(painter) ##painter.resetTransform() painter.restore() if option.state & QStyle.State_Selected: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(164,164,164,120))) painter.drawRoundedRect(selected_rect, 5, 5) #painter.fillRect(selected_rect, QColor(164,164,164,120)) painter.restore() if gallery.dead_link: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(255,0,0,120))) p_path = QPainterPath() p_path.setFillRule(Qt.WindingFill) p_path.addRoundedRect(selected_rect, 5,5) p_path.addRect(x,y, 20, 20) p_path.addRect(x+w-20,y, 20, 20) painter.drawPath(p_path.simplified()) painter.setPen(QColor("white")) txt_layout = misc.text_layout("Cannot find gallery source!", w, self.title_font, self.title_font_m) txt_layout.draw(painter, QPointF(x, y+h*0.3)) painter.restore() if app_constants.DEBUG: painter.save() painter.setBrush(QBrush(QColor("red"))) painter.setPen(QColor("white")) txt_l = self.title_font_m.width(str(gallery.id)) painter.drawRect(x, y+40, txt_l*2, self.title_font_m.height()) painter.drawText(x+1, y+51, str(gallery.id)) painter.restore() if option.state & QStyle.State_Selected: painter.setPen(QPen(option.palette.highlightedText().color())) else: super().paint(painter, option, index)
def paint(self, painter, option, index): painter.setRenderHint(QPainter.Antialiasing) provider_ui_item = index.data(Qt.UserRole) painter.save() painter.translate(self._padding + option.rect.x(), self._padding + option.rect.y()) w = h = (self._radius - self._padding) * 2 body_rect = QRect(0, 0, w, h) if provider_ui_item.colorful_svg: svg_renderer = QSvgRenderer(QUrl(provider_ui_item.colorful_svg).toString()) svg_renderer.render(painter, QRectF(body_rect)) else: # draw rounded rect painter.save() text_color = option.palette.color(QPalette.Text) if text_color.lightness() > 150: non_text_color = text_color.darker(140) else: non_text_color = text_color.lighter(150) non_text_color.setAlpha(100) pen = painter.pen() pen.setColor(non_text_color) painter.setPen(pen) painter.drawRoundedRect(body_rect, w//2, h//2) painter.restore() painter.save() font = painter.font() resize_font(font, -3) painter.setFont(font) text_option = QTextOption() text_option.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere) text_option.setAlignment(Qt.AlignCenter) text_rect = QRectF(self.__text_rect_x, self.__text_rect_x, self.__text_rect_width, self.__text_rect_width) painter.drawText(QRectF(text_rect), provider_ui_item.text, text_option) painter.restore() # TODO: use library.check_flags instead of provider.check_flags provider = provider_ui_item.provider if self._library.check_flags( provider.identifier, ModelType.none, PF.current_user): if provider.has_current_user(): painter.save() bottom_right = body_rect.bottomRight() status_radius = self._radius // 5 x = bottom_right.x() - status_radius * 2 y = bottom_right.y() - status_radius * 2 status_rect = QRect(QPoint(x, y), bottom_right) pen = painter.pen() pen.setWidth(2) pen.setColor(QGuiApplication.palette().color(QPalette.Window)) painter.setPen(pen) painter.setBrush(QColor(SOLARIZED_COLORS['blue'])) painter.drawRoundedRect(status_rect, status_radius, status_radius) painter.restore() painter.restore()
def print_html(printer): root = 'config.ini' basic_msg = configparser.ConfigParser() basic_msg.read(root) try: if not myconnect: raise TimeoutError code = basic_msg.get("msg", 'code') url = domain + "store/api/detail?code={}".format(code) req = requests.get(url=url) result_data = json.loads(req.text) except Exception as e: print(e) store = config.get_local_store_info() result_data = { 'data': { "pcId": store.id(), "pcPhone": store.phone(), "pcAddress": store.address(), "pcSign": store.name(), }, 'code': 200 } must_set = ['数量', '单价', '小计', '总价', '单位', '备注'] if result_data.get("code") != 200: store_name = "" pc_address = "" pc_phone = "" else: store_name = result_data.get("data").get("pcSign", "") pc_address = result_data.get("data").get("pcAddress", "") pc_phone = result_data.get("data").get("pcPhone", "") result = get_sale_info_by_one_key(selectOrderNo) fp = open("printer.txt", 'rb') data = fp.readline().decode().replace("\n", "").replace("\r", "").replace("\ufeff", "") fp.close() font_size = 7 if data: try: font_size = int(data) except Exception as e: print(e) font_size = 7 # *{font-size:65px;} if result: header = """<html> <style> table{ background-color:#000000; } .linetd{ text-align: center; width: 820px; color: red; height: 30px; } .halftd{ width: 410px; } #content{ text-align: center; position: relative; top: 50%; transform: translateY(-50%); } td{ padding:2px; align:center; border:1px solid black; background-color:#ffffff } """ + "*{font-size:" + str(font_size) + "pt;}" + ".bigWord{font-size:" + str( font_size * 1.5) + "pt;}" + "</style><head></head>" # *{font-size:50px;} td_width = 19 body = """ <body style="text-align: center;"> <table width=100% CELLPADDING="0" CELLSPACING="1" border="0"> <tr> <td class="bigWord" align="center" colspan="100" width="100%"> {storeName} </td> </tr> <tr> <td colspan="50">车牌号:{carId}</td> <td colspan="50">销售日期:{createdTime}</td> </tr> <tr> <td colspan="50">客户电话:{carPhone}</td> <td colspan="50">销售单号:<span style="">{orderNo}</span></td> </tr> <tr> <td colspan="100" height="20px"> </td> </tr> """.format(storeName=store_name, carId=result[0][2], createdTime=result[0][0], carPhone=result[0][4], orderNo=result[0][1]) content = "" seq = 1 total_price = 0 page = 0 page_height = 100 for order in result: page += 1 attribute = json.loads(order[8]) base_height = 180 # 手动排序 # mustSet = ['数量','单价','小计','总价','单位','备注'] # 去除mustset后的必然顺序为:"品牌","型号","工时费","更换里程" # 后面用字符串排序key来排序 temp_key_list2 = ["品牌", "型号", "工时费", "更换里程"] temp_key_list = list() for t in temp_key_list2: if attribute.get(t) and attribute.get(t) != '-': temp_key_list.append(t) for k, v in attribute.items(): if k not in must_set + ["品牌", "型号", "工时费", "更换里程"] and v != "-" and v != "" and k != "检索ID": temp_key_list.append(k) temp_key_list.sort() no_must_set = OrderedDict() for k in temp_key_list: no_must_set[k] = attribute.get(k) # 总长度要减去备注和名称,因为名称长度另外设置,备注不打印 td = "" key_dict = dict() i = 0 j = 0 td_list = list() key_list = list() page_height += int(len(no_must_set.keys()) / 5 + 1) * 60 + base_height for k, v in no_must_set.items(): # if k not in mustSet and v != "-" and v != "" and k!="检索ID" : td += "<td colspan=\"{tdWidth}\" align=\"center\"><b>{key}</b></td>".format(tdWidth=td_width, key=k) key_list.append(k) if i >= 4: i = 0 td_list.append(td) td = "" key_dict[j] = key_list key_list = list() j += 1 else: i += 1 # 补齐 if key_list: if len(key_list) < 5: num = len(key_list) for i in range(5 - num): key_list.append("") td += "<td colspan=\"{tdWidth}\" align=\"center\"></td>".format(tdWidth=td_width) td_list.append(td) key_dict[j] = key_list # 序号合并列数 merge_num = len(td_list) * 2 + 2 # createdTime,orderNo,carId,carUser,carPhone,carModel,workerName,project,brand," \ # "model,huawen,number,unitPrice,xiaoji,gongshi,ghlc,remark,totalPrice,pcId,unit content += """ <tr> <td colspan="5" align="center"><b>序</b></td> <td colspan="{tdWidth}" align="center"><b>名称</b></td> <td colspan="{tdWidth}" align="center"><b>单位</b></td> <td colspan="{tdWidth}" align="center"><b>数量</b></td> <td colspan="{tdWidth}" align="center"><b>单价</b></td> <td colspan="{tdWidth}" align="center"><b>小计</b></td> </tr> <tr> <td rowspan="{xuNum}" colspan="5" align="center"><br/>{xuhao}</td> <td colspan="{tdWidth}" align="center">{project}</td> <td colspan="{tdWidth}" align="center">{unit}</td> <td colspan="{tdWidth}" align="center">{number}</td> <td colspan="{tdWidth}" align="center">{unitPrice}</td> <td colspan="{tdWidth}" align="center">{xiaoji}</td> </tr> """.format(xuNum=merge_num, xuhao=seq, unit=attribute.get("单位", ""), number=attribute.get("数量", ""), unitPrice=attribute.get("单价", ""), xiaoji=attribute.get('小计', ""), project=order[7], tdWidth=td_width) more_content = "" ii = 0 for td in td_list: # 先放入表头 more_content += "<tr>" + td + "</tr>" # 再放入内容 more_content += """ <tr> <td colspan="{tdWidth}" align="center">{one}</td> <td colspan="{tdWidth}" align="center">{two}</td> <td colspan="{tdWidth}" align="center">{three}</td> <td colspan="{tdWidth}" align="center">{four}</td> <td colspan="{tdWidth}" align="center">{five}</td> </tr> """.format(tdWidth=td_width, one=attribute.get(key_dict[ii][0], ""), two=attribute.get(key_dict[ii][1], ""), three=attribute.get(key_dict[ii][2], ""), four=attribute.get(key_dict[ii][3], ""), five=attribute.get(key_dict[ii][4], "")) ii += 1 fenge = """ <tr> <td colspan="100" height="20px"> </td> </tr> """ zongjiaconetent = """ <tr> <td colspan="95">总价:{zongjia}</td> </tr> """.format(zongjia=attribute.get('总价', "")) content += more_content + zongjiaconetent + fenge seq += 1 try: total_price += float(attribute.get('总价', 0)) except Exception as e: print(e) total_price = 0 total_price = str(total_price) cn = cncurrency(total_price) foot = """ <tr> <td style="height:35px" colspan="70">合计人名币(大写):{cn}</td> <td style="height:35px" colspan="30">小写:{zongjia}</td> </tr> <tr> <td colspan="30">{storeName}</td> <td colspan="35">地址:{pcAddress}</td> <td colspan="35">联系电话:{pcPhone}</td> </tr> </table> </body> </html> """.format(cn=cn, zongjia=total_price, storeName=store_name, pcPhone=pc_phone, pcAddress=pc_address) html = header + body + content + foot text_document = QTextDocument() text_document.setHtml(html) text_document.setDocumentMargin(35) printer.setPageSize(QPrinter.Custom) # height = baseHeight+((page-1)*150) # printer.setPaperSize(QSizeF(printer.logicalDpiX()*(86/25.4),height),QPrinter.Point) # textDocument.setPageSize(QSizeF(printer.logicalDpiX()*(86/25.4),height)) printer.setPaperSize(QSizeF(581, page_height), QPrinter.Point) text_document.setPageSize(QSizeF(581, page_height)) textOp = QTextOption() textOp.setWrapMode(QTextOption.WrapAnywhere) textOp.setAlignment(Qt.AlignCenter) text_document.setDefaultTextOption(textOp) printer.setOutputFormat(QPrinter.NativeFormat) text_document.print(printer)
def paint(self, painter, option, index): assert isinstance(painter, QPainter) if index.data(Qt.UserRole+1): if app_constants.HIGH_QUALITY_THUMBS: painter.setRenderHint(QPainter.SmoothPixmapTransform) painter.setRenderHint(QPainter.Antialiasing) gallery = index.data(Qt.UserRole+1) title = gallery.title artist = gallery.artist title_color = app_constants.GRID_VIEW_TITLE_COLOR artist_color = app_constants.GRID_VIEW_ARTIST_COLOR label_color = app_constants.GRID_VIEW_LABEL_COLOR # Enable this to see the defining box #painter.drawRect(option.rect) # define font size if 20 > len(title) > 15: title_size = "font-size:{}px;".format(self.font_size) elif 30 > len(title) > 20: title_size = "font-size:{}px;".format(self.font_size-1) elif 40 > len(title) >= 30: title_size = "font-size:{}px;".format(self.font_size-2) elif 50 > len(title) >= 40: title_size = "font-size:{}px;".format(self.font_size-3) elif len(title) >= 50: title_size = "font-size:{}px;".format(self.font_size-4) else: title_size = "font-size:{}px;".format(self.font_size) if 30 > len(artist) > 20: artist_size = "font-size:{}px;".format(self.font_size) elif 40 > len(artist) >= 30: artist_size = "font-size:{}px;".format(self.font_size-1) elif len(artist) >= 40: artist_size = "font-size:{}px;".format(self.font_size-2) else: artist_size = "font-size:{}px;".format(self.font_size) #painter.setPen(QPen(Qt.NoPen)) #option.rect = option.rect.adjusted(11, 10, 0, 0) option.rect.setWidth(self.W) option.rect.setHeight(self.H) rec = option.rect.getRect() x = rec[0] y = rec[1] w = rec[2] h = rec[3] text_area = QTextDocument() text_area.setDefaultFont(option.font) text_area.setHtml(""" <head> <style> #area {{ display:flex; width:140px; height:10px }} #title {{ position:absolute; color: {4}; font-weight:bold; {0} }} #artist {{ position:absolute; color: {5}; top:20px; right:0; {1} }} </style> </head> <body> <div id="area"> <center> <div id="title">{2} </div> <div id="artist">{3} </div> </div> </center> </body> """.format(title_size, artist_size, title, artist, title_color, artist_color)) text_area.setTextWidth(w) #chapter_area = QTextDocument() #chapter_area.setDefaultFont(option.font) #chapter_area.setHtml(""" #<font color="black">{}</font> #""".format("chapter")) #chapter_area.setTextWidth(w) def center_img(width): new_x = x if width < w: diff = w - width offset = diff//2 new_x += offset return new_x # if we can't find a cached image pix_cache = QPixmapCache.find(self.key(gallery.profile)) if isinstance(pix_cache, QPixmap): self.image = pix_cache img_x = center_img(self.image.width()) if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) else: self.image = QPixmap(gallery.profile) img_x = center_img(self.image.width()) QPixmapCache.insert(self.key(gallery.profile), self.image) if self.image.height() < self.image.width(): #to keep aspect ratio painter.drawPixmap(QPoint(img_x,y), self.image) else: painter.drawPixmap(QPoint(img_x,y), self.image) # draw star if it's favorited if gallery.fav == 1: painter.drawPixmap(QPointF(x,y), QPixmap(app_constants.STAR_PATH)) if app_constants._REFRESH_EXTERNAL_VIEWER: if app_constants.USE_EXTERNAL_VIEWER: self.external_icon = self.file_icons.get_external_file_icon() else: self.external_icon = self.file_icons.get_default_file_icon() if gallery.state == self.G_DOWNLOAD: painter.save() dl_box = QRect(x, y, w, 20) painter.setBrush(QBrush(QColor(0,0,0,123))) painter.setPen(QColor('white')) painter.drawRect(dl_box) painter.drawText(dl_box, Qt.AlignCenter, 'Downloading...') painter.restore() else: if app_constants.DISPLAY_GALLERY_TYPE: self.type_icon = self.file_icons.get_file_icon(gallery.path) if self.type_icon and not self.type_icon.isNull(): self.type_icon.paint(painter, QRect(x+2, y+app_constants.THUMB_H_SIZE-16, 16, 16)) if app_constants.USE_EXTERNAL_PROG_ICO: if self.external_icon and not self.external_icon.isNull(): self.external_icon.paint(painter, QRect(x+w-30, y+app_constants.THUMB_H_SIZE-28, 28, 28)) def draw_text_label(lbl_h): #draw the label for text painter.save() painter.translate(x, y+app_constants.THUMB_H_SIZE) box_color = QBrush(QColor(label_color))#QColor(0,0,0,123)) painter.setBrush(box_color) rect = QRect(0, 0, w, lbl_h) #x, y, width, height painter.fillRect(rect, box_color) painter.restore() return rect if option.state & QStyle.State_MouseOver or\ option.state & QStyle.State_Selected: title_layout = self.text_layout(title, w, self.title_font, self.title_font_m) artist_layout = self.text_layout(artist, w, self.artist_font, self.artist_font_m) t_h = title_layout.boundingRect().height() a_h = artist_layout.boundingRect().height() if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(min(t_h+a_h+3, app_constants.GRIDBOX_LBL_H)) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) clipping = QRectF(x, y+app_constants.THUMB_H_SIZE, w, app_constants.GRIDBOX_LBL_H - 10) title_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE), clip=clipping) artist_layout.draw(painter, QPointF(x, y+app_constants.THUMB_H_SIZE+t_h), clip=clipping) #painter.fillRect(option.rect, QColor) else: if app_constants.GALLERY_FONT_ELIDE: lbl_rect = draw_text_label(self.text_label_h) else: lbl_rect = draw_text_label(app_constants.GRIDBOX_LBL_H) # draw text painter.save() alignment = QTextOption(Qt.AlignCenter) alignment.setUseDesignMetrics(True) title_rect = QRectF(0,0,w, self.title_font_m.height()) artist_rect = QRectF(0,self.artist_font_m.height(),w, self.artist_font_m.height()) painter.translate(x, y+app_constants.THUMB_H_SIZE) if app_constants.GALLERY_FONT_ELIDE: painter.setFont(self.title_font) painter.setPen(QColor(title_color)) painter.drawText(title_rect, self.title_font_m.elidedText(title, Qt.ElideRight, w-10), alignment) painter.setPen(QColor(artist_color)) painter.setFont(self.artist_font) alignment.setWrapMode(QTextOption.NoWrap) painter.drawText(artist_rect, self.title_font_m.elidedText(artist, Qt.ElideRight, w-10), alignment) else: text_area.setDefaultFont(QFont(self.font_name)) text_area.drawContents(painter) ##painter.resetTransform() painter.restore() if option.state & QStyle.State_Selected: painter.save() selected_rect = QRectF(x, y, w, lbl_rect.height()+app_constants.THUMB_H_SIZE) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor(164,164,164,120))) p_path = QPainterPath() p_path.setFillRule(Qt.WindingFill) p_path.addRoundedRect(selected_rect, 5,5) p_path.addRect(x,y, 20, 20) p_path.addRect(x+w-20,y, 20, 20) painter.drawPath(p_path.simplified()) #painter.fillRect(selected_rect, QColor(164,164,164,120)) painter.restore() #if option.state & QStyle.State_Selected: # painter.setPen(QPen(option.palette.highlightedText().color())) else: super().paint(painter, option, index)
def paint(self, painter, option, index): msg = index.model().data(index, Qt.DisplayRole) field = QRect(option.rect) field = field.marginsRemoved(variables.TEXT_PADDING) doc = QTextDocument(msg.text) doc.setDocumentMargin(0) opt = QTextOption() opt.setWrapMode(opt.WrapAtWordBoundaryOrAnywhere) doc.setDefaultTextOption(opt) doc.setDefaultFont(variables.font) if msg.user == variables.USER_ME: doc.setTextWidth(field.size().width() - 20 - 50) else: doc.setTextWidth(field.size().width() - 20) field.setHeight(int(doc.size().height())) field.setWidth(int(doc.idealWidth())) field = field.marginsAdded(variables.TEXT_PADDING) line_height = QFontMetrics(variables.font).lineSpacing( ) + variables.TEXT_PADDING.bottom() - variables.BUBBLE_PADDING.bottom( ) + variables.TEXT_PADDING.top() - variables.BUBBLE_PADDING.top() if msg.user == variables.USER_ME: rect = QRect(option.rect.right() - field.size().width() - 20, option.rect.top(), field.size().width(), field.size().height()) else: rect = QRect(20, option.rect.top(), field.size().width(), field.size().height()) bubblerect = rect.marginsRemoved(variables.BUBBLE_PADDING) textrect = rect.marginsRemoved(variables.TEXT_PADDING) if msg.user == variables.USER_ME: p1 = bubblerect.topRight() p2 = bubblerect.bottomLeft() + QPoint(-36, -int(line_height / 2)) else: p1 = bubblerect.topLeft() painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.NoPen) color = QColor(variables.BUBBLE_COLORS[msg.user]) painter.setBrush(color) painter.drawRoundedRect(bubblerect, 10, 10) painter.drawPolygon(p1 + QPoint(-20, 0), p1 + QPoint(20, 0), p1 + QPoint(0, 15)) if msg.user == variables.USER_ME: if msg.status == variables.STATUS_UNREAD: painter.setPen(Qt.NoPen) painter.setBrush(QColor(variables.STATUS_COLOR)) painter.drawEllipse(p2, 7, 7) elif msg.status == variables.STATUS_UNDELIVERED: pen = QPen(QColor(variables.STATUS_COLOR)) pen.setWidth(2) painter.setPen(pen) painter.setBrush(Qt.NoBrush) painter.drawEllipse(p2, 7, 7) painter.drawLine(p2, p2 + QPoint(0, -5)) painter.drawLine(p2, p2 + QPoint(3, 0)) painter.setPen(Qt.gray) painter.setFont(variables.font) painter.translate(textrect.x(), textrect.y()) textrectf = QRectF(textrect) textrectf.moveTo(0, 0) doc.drawContents(painter, textrectf) painter.translate(-textrect.x(), -textrect.y())
def paint_smallicon_view(self, painter: QPainter) -> None: self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height()) font = self.style.font fm = self.style.fm painter.setFont(font) self.paint_thumbnail(painter) if self.zoom_index in [0, 1]: text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) text_rect = QRect(QPoint(self.tile_rect.height() + 4, 0), QPoint(self.tile_rect.width(), self.tile_rect.height())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) painter.drawText(QRectF(text_rect), text, text_option) elif self.zoom_index in [2]: text_rect = QRect(QPoint(self.tile_rect.height() + 4, 0), QPoint(self.tile_rect.width() - 80, self.tile_rect.height())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect(QPoint(self.tile_rect.width() - 80, 0), QPoint(self.tile_rect.width(), self.tile_rect.height())) text = bytefmt.humanize(self.fileinfo.size()) text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option) else: top_left_text, top_right_text, bottom_left_text, bottom_right = self.make_text() row1_rect = QRect(QPoint(self.tile_rect.left() + self.tile_rect.height() + 8, self.tile_rect.top()), QPoint(self.tile_rect.right() - 8, self.tile_rect.top() + self.tile_rect.height() / 2)) row2_rect = QRect(QPoint(self.tile_rect.left() + self.tile_rect.height() + 8, self.tile_rect.top() + self.tile_rect.height() / 2), QPoint(self.tile_rect.right() - 8, self.tile_rect.bottom())) # row 1 text_rect = QRect(QPoint(row1_rect.left(), row1_rect.top()), QPoint(row1_rect.right() - 80, row1_rect.bottom())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect(QPoint(row1_rect.left() - 80, row1_rect.top()), QPoint(row1_rect.right(), row1_rect.bottom())) text = bytefmt.humanize(self.fileinfo.size()) text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option) # row 2 text_rect = QRect(QPoint(row2_rect.left(), row2_rect.top()), QPoint(row2_rect.right() - 80, row2_rect.bottom())) text = bottom_left_text text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect(QPoint(row2_rect.left() - 80, row2_rect.top()), QPoint(row2_rect.right(), row2_rect.bottom())) text = top_left_text text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option)
def paintEvent(self, event): painter = QPainter(self.viewport()) painter.fillRect(0, 0, self.viewport().width(), self.viewport().height(), QColor('#181818')) self.pos = self.verticalScrollBar().value() data_start = 0 data_end = 0 if len(self.data) > self.visible_lines(): data_start = self.pos data_end = self.pos + self.visible_lines() else: data_end = len(self.data) drawing_pos_y = 10 trace_depth = 0 fontMetrics = QFontMetrics(QFont(self.font)) text_options = QTextOption() text_options.setAlignment(Qt.AlignLeft) text_options.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere) for i, line in enumerate(self.data): if i == self.pos: break if line['event'] == 'leave': trace_depth -= 1 elif line['event'] == 'enter': trace_depth += 1 for i, line in enumerate(self.data[data_start:data_end]): if i > self.visible_lines(): break is_obj = False if isinstance(line['data'], str) and line['data'].startswith('{'): is_obj = True line['data'] = json.loads(line['data']) drawing_pos_x = 10 painter.setPen(QColor('#fff')) if line['event'] == 'leave': if trace_depth: trace_depth -= 1 drawing_pos_x += (trace_depth * 20) painter.setPen(QColor('crimson')) painter.setBrush(QColor('#222')) polygon = QPolygon() polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5))) painter.drawPolygon(polygon) elif line['event'] == 'enter': trace_depth += 1 drawing_pos_x += (trace_depth * 20) painter.setPen(QColor('yellowgreen')) painter.setBrush(QColor('#222')) polygon = QPolygon() polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 5, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y + self._char_height + (self._char_height * 0.5))) #polygon.append(QPoint(drawing_pos_x + 21, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5))) painter.drawPolygon(polygon) drawing_pos_x += 20 rect = QRectF(drawing_pos_x, drawing_pos_y, self.viewport().width() - 25 - drawing_pos_x, self._char_height + 10) if line['event'] == 'enter': arg_str = '(' for a in range(len(line['data'])): arg_str += 'arg_{0}, '.format(a) if len(line['data']): arg_str = arg_str[:-2] arg_str += ')' painter.drawText(rect, line['class'] + arg_str, option=text_options) else: painter.drawText(rect, line['class'], option=text_options) drawing_pos_y += self._char_height + 15 if isinstance(line['data'], str): if line['data']: rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, self.viewport().width() - drawing_pos_x - 25, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, line['data']) rect = QRectF(drawing_pos_x, drawing_pos_y, rect.width(), rect.height()) painter.setPen(QColor('#888')) painter.drawText(rect, line['data'], option=text_options) drawing_pos_y += rect.height() + 5 else: width = int(floor(self.viewport().width() - drawing_pos_x - (5 * self._char_width) - 35)) max_chars = int(floor(width / self._char_width)) hold_x = drawing_pos_x + 5 width -= 20 painter.setPen(QColor('#888')) for data in line['data']: drawing_pos_x = hold_x if isinstance(line['data'][data], int): text = '{0:d}'.format(line['data'][data]) elif isinstance(line['data'][data], str): text = line['data'][data] elif isinstance(line['data'][data], list): text = str(line['data'][data]) else: text = str(line['data'][data]) if line['event'] == 'enter': arg = 'arg_{0}: '.format(data) painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, arg) drawing_pos_x += len(arg) * self._char_width elif line['event'] == 'leave': retval = data + ': ' painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, retval) drawing_pos_x += len(retval) * self._char_width if len(text) * self._char_width < width: painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, text) drawing_pos_y += self._char_height + 5 else: rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, width, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, text) rect = QRectF(rect) painter.drawText(rect, text, option=text_options) drawing_pos_y += rect.height() + 5 drawing_pos_y += self._char_height + 5
def paint_smallicon_view(self, painter: QPainter) -> None: self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height()) font = self.style.font fm = self.style.fm painter.setFont(font) self.paint_thumbnail(painter) if self.zoom_index in [0, 1]: text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) text_rect = QRect( QPoint(self.tile_rect.height() + 4, 0), QPoint(self.tile_rect.width(), self.tile_rect.height())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) painter.drawText(QRectF(text_rect), text, text_option) elif self.zoom_index in [2]: text_rect = QRect( QPoint(self.tile_rect.height() + 4, 0), QPoint(self.tile_rect.width() - 80, self.tile_rect.height())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect( QPoint(self.tile_rect.width() - 80, 0), QPoint(self.tile_rect.width(), self.tile_rect.height())) text = bytefmt.humanize(self.fileinfo.size()) text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option) else: top_left_text, top_right_text, bottom_left_text, bottom_right = self.make_text( ) row1_rect = QRect( QPoint(self.tile_rect.left() + self.tile_rect.height() + 8, self.tile_rect.top()), QPoint(self.tile_rect.right() - 8, self.tile_rect.top() + self.tile_rect.height() / 2)) row2_rect = QRect( QPoint(self.tile_rect.left() + self.tile_rect.height() + 8, self.tile_rect.top() + self.tile_rect.height() / 2), QPoint(self.tile_rect.right() - 8, self.tile_rect.bottom())) # row 1 text_rect = QRect( QPoint(row1_rect.left(), row1_rect.top()), QPoint(row1_rect.right() - 80, row1_rect.bottom())) text = self.fileinfo.basename() text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect(QPoint(row1_rect.left() - 80, row1_rect.top()), QPoint(row1_rect.right(), row1_rect.bottom())) text = bytefmt.humanize(self.fileinfo.size()) text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option) # row 2 text_rect = QRect( QPoint(row2_rect.left(), row2_rect.top()), QPoint(row2_rect.right() - 80, row2_rect.bottom())) text = bottom_left_text text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.drawText(QRectF(text_rect), text, text_option) text_rect = QRect(QPoint(row2_rect.left() - 80, row2_rect.top()), QPoint(row2_rect.right(), row2_rect.bottom())) text = top_left_text text = fm.elidedText(text, Qt.ElideRight, text_rect.width()) text_option = QTextOption(Qt.AlignRight | Qt.AlignVCenter) text_option.setWrapMode(QTextOption.NoWrap) painter.setPen(QColor(96, 96, 96)) painter.drawText(QRectF(text_rect), text, text_option)