def paint(self, painter, option, index): painter.save() painter.setRenderHint(QPainter.Antialiasing) rect = option.rect text_rect_height = 30 cover_spacing = 0 text_y = rect.y() + rect.height() - text_rect_height cover_height = rect.height() - text_rect_height cover_width = rect.width() - cover_spacing cover_x = rect.x() + cover_spacing // 2 cover_y = rect.y() text_rect = QRectF(rect.x(), text_y + 5, rect.width(), text_rect_height) obj = index.data(Qt.DecorationRole) if obj is None: painter.restore() return elif isinstance(obj, QColor): color = obj brush = QBrush(color) painter.setBrush(brush) painter.drawRect(cover_x, cover_y, cover_width, cover_height) else: pixmap = obj.scaledToWidth(cover_width, Qt.SmoothTransformation) painter.drawPixmap(cover_x, cover_y, pixmap) option = QTextOption() option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) album_name = index.data(Qt.DisplayRole) painter.drawText(text_rect, album_name, option) painter.restore()
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 __init__(self, theParent, theProject): QTextBrowser.__init__(self) logger.debug("Initialising DocViewer ...") # Class Variables self.mainConf = nw.CONFIG self.theProject = theProject self.theParent = theParent self.theTheme = theParent.theTheme self.theHandle = None self.qDocument = self.document() self.setMinimumWidth(300) self.setOpenExternalLinks(False) self.initViewer() theOpt = QTextOption() if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) self.qDocument.setDefaultTextOption(theOpt) self.anchorClicked.connect(self._linkClicked) self.setFocusPolicy(Qt.StrongFocus) logger.debug("DocViewer initialisation complete") return
def initViewer(self): """Set editor settings from main config. """ self._makeStyleSheet() # Set Font theFont = QFont() if self.mainConf.textFont is None: # If none is defined, set the default back to config self.mainConf.textFont = self.qDocument.defaultFont().family() theFont.setFamily(self.mainConf.textFont) theFont.setPointSize(self.mainConf.textSize) self.setFont(theFont) docPalette = self.palette() docPalette.setColor(QPalette.Base, QColor(*self.theTheme.colBack)) docPalette.setColor(QPalette.Text, QColor(*self.theTheme.colText)) self.setPalette(docPalette) self.qDocument.setDocumentMargin(self.mainConf.textMargin) theOpt = QTextOption() if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) self.qDocument.setDefaultTextOption(theOpt) # If we have a document open, we should reload it in case the font changed if self.theHandle is not None: tHandle = self.theHandle self.clearViewer() self.loadText(tHandle) return True
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 initViewer(self): """Set editor settings from main config. """ self._makeStyleSheet() # Set Font theFont = QFont() if self.mainConf.textFont is None: # If none is defined, set the default back to config self.mainConf.textFont = self.document().defaultFont().family() theFont.setFamily(self.mainConf.textFont) theFont.setPointSize(self.mainConf.textSize) self.setFont(theFont) # Set the widget colours to match syntax theme mainPalette = self.palette() mainPalette.setColor(QPalette.Window, QColor(*self.mainTheme.colBack)) mainPalette.setColor(QPalette.Base, QColor(*self.mainTheme.colBack)) mainPalette.setColor(QPalette.Text, QColor(*self.mainTheme.colText)) self.setPalette(mainPalette) docPalette = self.viewport().palette() docPalette.setColor(QPalette.Base, QColor(*self.mainTheme.colBack)) docPalette.setColor(QPalette.Text, QColor(*self.mainTheme.colText)) self.viewport().setPalette(docPalette) self.docHeader.matchColours() self.docFooter.matchColours() # Set default text margins self.document().setDocumentMargin(0) theOpt = QTextOption() if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) self.document().setDefaultTextOption(theOpt) # Scroll bars if self.mainConf.hideVScroll: self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) else: self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) if self.mainConf.hideHScroll: self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) else: self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Refresh the tab stops if self.mainConf.verQtValue >= 51000: self.setTabStopDistance(self.mainConf.getTabWidth()) else: self.setTabStopWidth(self.mainConf.getTabWidth()) # If we have a document open, we should reload it in case the font changed if self._docHandle is not None: self.reloadText() return True
def paintEvent(self, e): painter = QPainter(self) if self._size_grip.isVisible(): painter.save() painter.setPen(QColor('white')) option = QTextOption() option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) rect = QRect(self._size_grip.pos(), self._size_grip.size()) painter.drawText(QRectF(rect), '●', option) painter.restore()
def paintEvent(self, e): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.NoPen) painter.setBrush(self.palette().color(QPalette.Window)) painter.drawRoundedRect(self.rect(), self._border_radius, self._border_radius) painter.save() painter.setPen(QColor('white')) option = QTextOption() option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) rect = QRect(self.mapToParent(self._size_grip.pos()), self._size_grip.size()) painter.drawText(QRectF(rect), '●', option) painter.restore()
def fontValuePixmap(font): f = QFont(font) img = QImage(16, 16, QImage.Format_ARGB32_Premultiplied) img.fill(0) p = QPainter(img) p.setRenderHint(QPainter.TextAntialiasing, True) p.setRenderHint(QPainter.Antialiasing, True) f.setPointSize(13) p.setFont(f) t = QTextOption() t.setAlignment(Qt.AlignCenter) p.drawText(QRectF(0, 0, 16, 16), 'A', t) p.end() return QPixmap.fromImage(img)
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 paint(self, painter, option, index): painter.save() painter.setRenderHint(QPainter.Antialiasing) rect = option.rect text_rect_height = TextHeight cover_spacing = 0 text_y = rect.y() + rect.height() - text_rect_height cover_height = rect.height() - text_rect_height cover_width = rect.width() - cover_spacing cover_x = rect.x() + cover_spacing // 2 cover_y = rect.y() text_rect = QRectF(rect.x(), text_y, rect.width(), text_rect_height) obj = index.data(Qt.DecorationRole) if obj is None: painter.restore() return 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) painter.save() pen = painter.pen() pen.setColor(non_text_color) painter.setPen(pen) painter.translate(cover_x, cover_y) cover_rect = QRect(0, 0, cover_width, cover_height) if isinstance(obj, QColor): color = obj brush = QBrush(color) painter.setBrush(brush) else: pixmap = obj.scaledToWidth(cover_width, Qt.SmoothTransformation) brush = QBrush(pixmap) painter.setBrush(brush) painter.drawRoundedRect(cover_rect, 3, 3) painter.restore() option = QTextOption() option.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) album_name = index.data(Qt.DisplayRole) fm = QFontMetrics(painter.font()) elided_album_name = fm.elidedText(album_name, Qt.ElideRight, text_rect.width()) painter.drawText(text_rect, elided_album_name, option) painter.restore()
def initEditor(self): """Initialise or re-initialise the editor with the user's settings. This function is both called when the editor is created, and when the user changes the main editor preferences. """ # Reload dictionaries self.setDictionaries() # Set Font theFont = QFont() if self.mainConf.textFont is None: # If none is defined, set the default back to config self.mainConf.textFont = self.qDocument.defaultFont().family() theFont.setFamily(self.mainConf.textFont) theFont.setPointSize(self.mainConf.textSize) self.setFont(theFont) docPalette = self.palette() docPalette.setColor(QPalette.Base, QColor(*self.theTheme.colBack)) docPalette.setColor(QPalette.Text, QColor(*self.theTheme.colText)) self.setPalette(docPalette) # Set default text margins self.qDocument.setDocumentMargin(self.mainConf.textMargin) # Also set the document text options for the document text flow theOpt = QTextOption() if self.mainConf.tabWidth is not None: if self.mainConf.verQtValue >= 51000: theOpt.setTabStopDistance(self.mainConf.tabWidth) if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) self.qDocument.setDefaultTextOption(theOpt) self.hLight.initHighlighter() # If we have a document open, we should reload it in case the font changed if self.theHandle is not None: tHandle = self.theHandle self.clearEditor() self.loadText(tHandle) self.changeWidth() return True
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 _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 __init__(self, theParent, theProject): QTextBrowser.__init__(self) logger.debug("Initialising DocViewer ...") # Class Variables self.mainConf = nw.CONFIG self.theProject = theProject self.theParent = theParent self.theTheme = theParent.theTheme self.theHandle = None self.qDocument = self.document() self.setMinimumWidth(300) self.initViewer() theOpt = QTextOption() if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) self.qDocument.setDefaultTextOption(theOpt) logger.debug("DocViewer initialisation complete") return
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(self, painter, option, index): painter.save() painter.setRenderHint(QPainter.Antialiasing) rect = option.rect text_rect_height = 30 img_text_height = self.view.img_text_height source_rect_height = img_text_height - text_rect_height text_y = rect.y() + rect.height() - img_text_height cover_height = rect.height() - img_text_height cover_width = rect.width() text_rect = QRectF(rect.x(), text_y, rect.width(), text_rect_height) source_rect = QRectF(rect.x(), text_y + text_rect_height - 5, rect.width(), source_rect_height + 5) obj = index.data(Qt.DecorationRole) if obj is None: painter.restore() return 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) painter.save() pen = painter.pen() pen.setColor(non_text_color) painter.setPen(pen) painter.translate(rect.x(), rect.y()) if isinstance(obj, QColor): color = obj brush = QBrush(color) painter.setBrush(brush) else: if obj.height() < obj.width(): pixmap = obj.scaledToHeight(cover_height, Qt.SmoothTransformation) else: pixmap = obj.scaledToWidth(cover_width, Qt.SmoothTransformation) brush = QBrush(pixmap) painter.setBrush(brush) border_radius = 3 if self.as_circle: border_radius = cover_width // 2 cover_rect = QRect(0, 0, cover_width, cover_height) painter.drawRoundedRect(cover_rect, border_radius, border_radius) painter.restore() option = QTextOption() source_option = QTextOption() if self.as_circle: option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) source_option.setAlignment(Qt.AlignHCenter | Qt.AlignTop) else: option.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) source_option.setAlignment(Qt.AlignLeft | Qt.AlignTop) name = index.data(Qt.DisplayRole) fm = QFontMetrics(painter.font()) elided_name = fm.elidedText(name, Qt.ElideRight, text_rect.width()) source = index.data(Qt.WhatsThisRole) painter.drawText(text_rect, elided_name, option) painter.restore() painter.save() pen = painter.pen() font = painter.font() resize_font(font, -2) painter.setFont(font) pen.setColor(non_text_color) painter.setPen(non_text_color) painter.drawText(source_rect, source, source_option) 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): 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 paintEvent(self, e): painter = QPainter(self) option = QTextOption() option.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) painter.drawText(QRectF(self.rect()), '●', option)
def initEditor(self): """Initialise or re-initialise the editor with the user's settings. This function is both called when the editor is created, and when the user changes the main editor preferences. """ # Some Constants self.nonWord = "\"'" self.nonWord += "".join(self.mainConf.fmtDoubleQuotes) self.nonWord += "".join(self.mainConf.fmtSingleQuotes) # Reload spell check and dictionaries self._setupSpellChecking() self.setDictionaries() # Set font theFont = QFont() if self.mainConf.textFont is None: # If none is defined, set the default back to config self.mainConf.textFont = self.qDocument.defaultFont().family() theFont.setFamily(self.mainConf.textFont) theFont.setPointSize(self.mainConf.textSize) self.setFont(theFont) docPalette = self.palette() docPalette.setColor(QPalette.Base, QColor(*self.theTheme.colBack)) docPalette.setColor(QPalette.Text, QColor(*self.theTheme.colText)) self.setPalette(docPalette) # Set default text margins self.qDocument.setDocumentMargin(self.mainConf.textMargin) # Also set the document text options for the document text flow theOpt = QTextOption() if self.mainConf.tabWidth is not None: if self.mainConf.verQtValue >= 51000: theOpt.setTabStopDistance(self.mainConf.tabWidth) if self.mainConf.doJustify: theOpt.setAlignment(Qt.AlignJustify) if self.mainConf.showTabsNSpaces: theOpt.setFlags(theOpt.flags() | QTextOption.ShowTabsAndSpaces) if self.mainConf.showLineEndings: theOpt.setFlags(theOpt.flags() | QTextOption.ShowLineAndParagraphSeparators) self.qDocument.setDefaultTextOption(theOpt) # Initialise the syntax highlighter self.hLight.initHighlighter() # If we have a document open, we should reload it in case the # font changed, otherwise we just clear the editor entirely, # which makes it read only. if self.theHandle is not None: # We must save the current handle as clearEditor() sets it # to None tHandle = self.theHandle self.clearEditor() self.loadText(tHandle) self.updateDocMargins() else: self.clearEditor() return True
def initTextOption(): option = QTextOption() option.setAlignment(Qt.AlignCenter) return option