def paint(self, painter, option, index): """Render the delegate for the item.""" if index.column() != self._html_column: return QStyledItemDelegate.paint(self, painter, option, index) options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) if options.widget is None: style = QApplication.style() else: style = options.widget.style() doc = QTextDocument() doc.setHtml(options.text) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def paint(self, painter, option, index): optionV4 = QStyleOptionViewItemV4(option) self.initStyleOption(optionV4, index) style = optionV4.widget.style() if optionV4.widget else QApplication.style() doc = QTextDocument() doc.setHtml(optionV4.text) # painting item without text optionV4.text = QString() style.drawControl(QStyle.CE_ItemViewItem, optionV4, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Hilight text if item is selected if optionV4.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, optionV4.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, optionV4) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) style = QApplication.style( ) if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor( QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def drawContents(self, painter): """ Reimplementation of drawContents to limit the drawing inside `textRext`. """ painter.setPen(self.__color) painter.setFont(self.font()) if self.__textRect: rect = self.__textRect else: rect = self.rect().adjusted(5, 5, -5, -5) if Qt.mightBeRichText(self.__message): doc = QTextDocument() doc.setHtml(self.__message) doc.setTextWidth(rect.width()) cursor = QTextCursor(doc) cursor.select(QTextCursor.Document) fmt = QTextBlockFormat() fmt.setAlignment(self.__alignment) cursor.mergeBlockFormat(fmt) painter.save() painter.translate(rect.topLeft()) doc.drawContents(painter) painter.restore() else: painter.drawText(rect, self.__alignment, self.__message)
class FeatureShape(LabeledPolygonShape): def draw(self, painter, xMap, yMap, canvasRect): self._setup_painter(painter) self._set_outer_pen_and_brush(painter, xMap, yMap) rtmin = self.item.rtmin rtmax = self.item.rtmax mzmin = self.item.mzmin mzmax = self.item.mzmax self._draw_polygon(painter, xMap, yMap, (rtmin, rtmax, mzmin, mzmax)) self._set_inner_pen_and_brush(painter, xMap, yMap) for mass_trace in self.item.mass_traces: self._draw_polygon(painter, xMap, yMap, mass_trace) if self.label is not None: self._draw_label(painter, xMap, yMap) def _draw_label(self, painter, xMap, yMap): self.text = QTextDocument() self.text.setDefaultStyleSheet("""div { color: rgb(%d, %d, %d); }""" % self.color) self.text.setHtml("<div>%s</div>" % (self.label, )) x0 = xMap.transform(self.item.rtmax) # y0: height between m0 and m1 masstrace if m1 exists, else at height of m0 yi = sorted(m.mzmin for m in self.item.mass_traces) if len(yi) >= 2: y0 = yMap.transform(0.5 * yi[0] + 0.5 * yi[1]) else: y0 = yMap.transform(yi[0]) h = self.text.size().height() painter.translate(x0, y0 - 0.5 * h) self.text.drawContents(painter)
def __render_fullname(self, width, index): fullname = index.data(self.FullnameRole).toPyObject() doc = QTextDocument() doc.setHtml("<b>%s</b>" % fullname) doc.setDefaultFont(FULLNAME_FONT) doc.setTextWidth(self.__calculate_text_width(width)) return doc
def sizeHint(self, option, index): text = index.model().data(index).toString() document = QTextDocument() document.setDefaultFont(option.font) document.setHtml(text) return QSize(document.idealWidth() + 5, option.fontMetrics.height())
def paint(self, painter, option, index): """QStyledItemDelegate.paint implementation """ option.state &= ~QStyle.State_HasFocus # never draw focus rect options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setDocumentMargin(1) doc.setHtml(options.text) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected if option.state & QStyle.State_Selected: ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText)) textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def savePdf(self): """ Save to pdf file """ fileName = QFileDialog.getSaveFileName( self, 'Save to PDF', "", "PDF file (*.pdf);;All Files (*.*)") # new in v17.1 if QtHelper.IS_QT5: _filename, _type = fileName else: _filename = fileName # end of new if _filename: printer = QPrinter(QPrinter.HighResolution) printer.setPageSize(QPrinter.A4) printer.setColorMode(QPrinter.Color) printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(_filename) doc = QTextDocument() if self.toXml: doc.setPlainText(self.txtEdit.text()) else: doc.setHtml(self.txtEdit.toHtml()) doc.print_(printer)
def stamp_image(image, expression_str, position, feature): painter = QPainter(image) data = QgsExpression.replaceExpressionText(expression_str, feature, None) if not data: return image data = data.replace(r"\n", "<br>") style = """ body { color: yellow; } """ doc = QTextDocument() doc.setDefaultStyleSheet(style) data = "<body>{}</body>".format(data) doc.setHtml(data) point = QPointF(20, 20) # Wrap the text so we don't go crazy if doc.size().width() > 300: doc.setTextWidth(300) if position == "top-left": point = QPointF(20, 20) elif position == "top-right": x = image.width() - 20 - doc.size().width() point = QPointF(x, 20) elif position == "bottom-left": point = QPointF(20, image.height() - 20 - doc.size().height()) elif position == "bottom-right": x = image.width() - 20 - doc.size().width() y = image.height() - 20 - doc.size().height() point = QPointF(x, y) painter.translate(point) doc.drawContents(painter) return image
def _copy(self, index): doc = QTextDocument() doc.setHtml(index.data(Qt.DisplayRole).toString()) clipboard = QApplication.clipboard() richTextData = QMimeData() richTextData.setHtml(index.data(Qt.DisplayRole).toString()) richTextData.setText(doc.toPlainText()) clipboard.setMimeData(richTextData)
def sizeHint(self, option, index): options = QStyleOptionViewItemV4(option) self.initStyleOption(options,index) doc = QTextDocument() doc.setHtml(options.text) doc.setTextWidth(options.rect.width()) return QtCore.QSize(doc.idealWidth(), doc.size().height())
def sizeHint(self, option, index): options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) doc = QTextDocument() doc.setHtml(options.text) doc.setTextWidth(options.rect.width()) return QtCore.QSize(doc.idealWidth(), doc.size().height())
def sizeHint(self, option, index): optionV4 = QStyleOptionViewItemV4(option) self.initStyleOption(optionV4, index) doc = QTextDocument() doc.setHtml(optionV4.text) doc.setTextWidth(optionV4.rect.width()) return QSize(doc.idealWidth(), max(doc.size().height(), optionV4.decorationSize.height()))
def sizeHint(self, option, index): """Calculate the needed size.""" options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) doc = QTextDocument() doc.setHtml(options.text) doc.setTextWidth(options.rect.width()) return QSize(doc.idealWidth(), doc.size().height())
def writePdf(dir_): newbody = originHTML.format(**htmlpara) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_+'.pdf') printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def writePdf(dir_): newbody = originHTML.format(**htmlpara) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_ + '.pdf') printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def sizeHint(self, option, index): fm = option.fontMetrics if index.column() in (SRC_ADDR, DST_ADDR): text = index.model().data(index).toString() document = QTextDocument() document.setDefaultFont(option.font) document.setHtml(text) #document.setPageSize(option.rect.size()) return QSize(document.idealWidth() + 5, 1.3 * fm.height()) return QItemDelegate.sizeHint(self, option, index)
def __render_status_message(self, width, index): message = unicode(index.data(self.MessageRole).toPyObject()) urls = index.data(self.URLsEntitiesRole).toPyObject() for url in urls: pretty_url = "<a href='%s'>%s</a>" % (url.url, url.display_text) message = message.replace(url.search_for, pretty_url) doc = QTextDocument() doc.setHtml(message) doc.setTextWidth(self.__calculate_text_width(width)) return doc
def __render_username(self, width, index): username_string = index.data(self.UsernameRole).toPyObject() username = QTextDocument() if username_string != '': username.setHtml("<span style='color: #666;'>@%s</span>" % username_string) else: username.setHtml("<span style='color: #666;'></span>" % username_string) username.setDefaultFont(USERNAME_FONT) username.setTextWidth(self.__calculate_text_width(width)) return username
def sizeHint(self, option, index): """QStyledItemDelegate.sizeHint implementation """ options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) doc = QTextDocument() doc.setDocumentMargin(1) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) doc.setHtml(options.text) return QSize(doc.idealWidth(), doc.size().height())
def sizeHint(self, option, index): fm = option.fontMetrics if index.column() == TEU: return QSize(fm.width("9,999,999"), fm.height()) if index.column() == DESCRIPTION: text = index.model().data(index).toString() document = QTextDocument() document.setDefaultFont(option.font) document.setHtml(text) return QSize(document.idealWidth() + 5, fm.height()) return QStyledItemDelegate.sizeHint(self, option, index)
def sizeHint(self, option, index): """QStyledItemDelegate.sizeHint implementation """ options = QStyleOptionViewItemV4(option) self.initStyleOption(options,index) doc = QTextDocument() doc.setDocumentMargin(1) # bad long (multiline) strings processing doc.setTextWidth(options.rect.width()) doc.setHtml(options.text) return QSize(doc.idealWidth(), doc.size().height())
def sizeHint( self, option, index ): fm = option.fontMetrics if index.column() in ( NOMBRE, TELEFONO, RUC, EMAIL ): text = index.model().data( index ).toString() document = QTextDocument() document.setDefaultFont( option.font ) document.setHtml( text ) return QSize( document.idealWidth() + 5, fm.height() ) elif index.column() == ACTIVO: return QSize( fm.width( "9" ), fm.height() ) else: return QStyledItemDelegate.sizeHint( self, option, index )
def sizeHint(self, option, index): """ Reimplements the :meth:`QStyledItemDelegate.sizeHint` method. """ document = QTextDocument() document.setDefaultFont(option.font) data = index.model().data(index) text = umbra.ui.common.getQVariantAsString(data) self.__label.setText(text) document.setHtml(text) return QSize(document.idealWidth() + self.__indent, option.fontMetrics.height())
def printDocument1(self): html = u"" date = QDate.currentDate().toString(self.DATE_FORMAT) address = Qt.escape("Bario francisco mesa").replace(",", "<br>") contact = Qt.escape("Luis Mejia") balance = 5000 html += ("<p align=right><img src=':/logo.png'></p>" "<p> align = right>Greasy hands ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>%s</p>" "<p>%s</p><p>Dear %s, </p>" "<p>The balance of your account is %s.") % ( date, address, contact, QString("$ %L1").arg( float(balance), 0, "f", 2)) if balance < 0: html += ( "<p><font color =red><b> Please remit the amount owing immediately.</b></font>" ) else: html += "We are delighted to have done business with you." html += ( "</p><p> </p><p>" "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>" ) transactions = [(QDate.currentDate(), 500), (QDate.currentDate(), 500), (QDate.currentDate(), -500), (QDate.currentDate(), 500)] for date, amount in transactions: color, status = "black", "Credit" if amount < 0: color, status = "red", "Debid" html += ( "<tr>" "<td align= right>%s</td>" "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % (date.toString(self.DATE_FORMAT), status, color, QString("$ %L1").arg(float(abs(amount)), 0, "f", 2))) html += ("</table></p><p style='page-break-after=always;'>" "We hope to continue doing business with you</p>") pdialog = QPrintDialog() if pdialog.exec_() == QDialog.Accepted: printer = pdialog.printer() document = QTextDocument() document.setHtml(html) document.print_(printer)
def init_print(self, linenos=True, style="default"): app = QApplication(sys.argv) # noqa doc = QTextDocument() doc.setHtml( self.highlight_file(linenos=linenos, style=style) ) printer = QPrinter() printer.setOutputFileName(self.pdf_file) printer.setOutputFormat(QPrinter.PdfFormat) page_size_dict = {"a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4} printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4)) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) doc.print_(printer) logging.info("PDF created at %s" % (self.pdf_file))
def writePdfabs(dir_): updates = SETTING().get('pdfpara') htmlpara.update(updates) newbody = originHTML.format(**htmlpara) # with open('t.html', 'wb') as f: # f.write(newbody) # f.close() printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_) printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def writePdfabs(dir_): updates = PDF_PARAMETER htmlpara.update(updates) newbody = originHTML.format(**htmlpara) # with open('t.html', 'wb') as f: # f.write(newbody) # f.close() printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(dir_) printer.setPageSize(QPrinter.A4) text = QTextDocument() text.setHtml(newbody.decode('utf-8')) text.print_(printer)
def renderLabel(self, painter): """Render the current timestamp on the map canvas""" if not self.showLabel or not self.model.hasLayers() or not self.dock.pushButtonToggleTime.isChecked(): return dt = self.model.getCurrentTimePosition() if dt is None: return labelString = self.labelOptions.getLabel(dt) # Determine placement of label given cardinal directions flags = 0 for direction, flag in ('N', Qt.AlignTop), ('S', Qt.AlignBottom), ('E', Qt.AlignRight), ('W', Qt.AlignLeft): if direction in self.labelOptions.placement: flags |= flag # Get canvas dimensions width = painter.device().width() height = painter.device().height() painter.setRenderHint(painter.Antialiasing, True) txt = QTextDocument() html = """<span style="background-color:%s; padding: 5px; font-size: %spx;"> <font face="%s" color="%s">%s</font> </span> """\ % (self.labelOptions.bgcolor, self.labelOptions.size, self.labelOptions.font, self.labelOptions.color, labelString) txt.setHtml(html) layout = txt.documentLayout() size = layout.documentSize() if flags & Qt.AlignRight: x = width - 5 - size.width() elif flags & Qt.AlignLeft: x = 5 else: x = width / 2 - size.width() / 2 if flags & Qt.AlignBottom: y = height - 5 - size.height() elif flags & Qt.AlignTop: y = 5 else: y = height / 2 - size.height() / 2 painter.translate(x, y) layout.draw(painter, QAbstractTextDocumentLayout.PaintContext()) painter.translate(-x, -y) # translate back
def printDocument1(self): html = u"" date = QDate.currentDate().toString(self.DATE_FORMAT) address = Qt.escape("Bario francisco mesa").replace(",","<br>") contact = Qt.escape("Luis Mejia") balance = 5000 html += ("<p align=right><img src=':/logo.png'></p>" "<p> align = right>Greasy hands ltd." "<br>New Lombard Street" "<br>London<br>WC13 4PX<br>%s</p>" "<p>%s</p><p>Dear %s, </p>" "<p>The balance of your account is %s.")% ( date, address, contact, QString("$ %L1").arg(float(balance),0,"f",2)) if balance <0 : html += ("<p><font color =red><b> Please remit the amount owing immediately.</b></font>") else: html += "We are delighted to have done business with you." html += ("</p><p> </p><p>" "<table border=1 cellpadding=2 cellspacing=2><tr><td colspan=3>Transaction</td></tr>") transactions = [ (QDate.currentDate(),500), (QDate.currentDate(),500), (QDate.currentDate(),-500), (QDate.currentDate(),500) ] for date, amount in transactions: color, status = "black", "Credit" if amount <0: color, status = "red", "Debid" html += ("<tr>" "<td align= right>%s</td>" "<td>%s</td><td align=right><font color=%s>%s</font></td></tr>" % ( date.toString(self.DATE_FORMAT), status,color, QString("$ %L1").arg(float(abs(amount)), 0, "f",2))) html += ("</table></p><p style='page-break-after=always;'>" "We hope to continue doing business with you</p>") pdialog = QPrintDialog() if pdialog.exec_() == QDialog.Accepted: printer = pdialog.printer() document = QTextDocument() document.setHtml(html) document.print_(printer)
def sizeHint(self, option, index): """ This method is re-implemented because Description column is using HTML, it must return the exactly number of characters for presentation purpose rather than the number of HTML raw characters. """ fm = option.fontMetrics if index.column() == TEU: return QSize(fm.width("9,999,999"), fm.height()) if index.column() == DESCRIPTION: text = index.model().data(index).toString() document = QTextDocument() document.setDefaultFont(option.font) document.setHtml(text) return QSize(document.idealWidth() + 5, fm.height()) return QStyledItemDelegate.sizeHint(self, option, index)
class HtmlItemDelegate(QItemDelegate): def __init__(self, parent): QItemDelegate.__init__(self, parent) self.document = QTextDocument(self) self.document.setDocumentMargin(0) self.hl_color = QApplication.palette().highlight().color() self.hl_color = ",".join([repr(self.hl_color.red()), repr(self.hl_color.green()), repr(self.hl_color.blue())]) def drawDisplay(self, painter, option, rect, text): point = rect.topLeft() painter.translate(point) if option.state & QStyle.State_Selected: text = "<div style='background-color: rgb(%s)'>%s</div>" % (self.hl_color, text) self.document.setHtml(text) self.document.drawContents(painter) painter.translate(-point)
def init_print(self, linenos=True, style="default"): app = QApplication(sys.argv) # noqa doc = QTextDocument() doc.setHtml(self.highlight_file(linenos=linenos, style=style)) printer = QPrinter() printer.setOutputFileName(self.pdf_file) printer.setOutputFormat(QPrinter.PdfFormat) page_size_dict = { "a2": QPrinter.A2, "a3": QPrinter.A3, "a4": QPrinter.A4 } printer.setPageSize(page_size_dict.get(self.size.lower(), QPrinter.A4)) printer.setPageMargins(15, 15, 15, 15, QPrinter.Millimeter) doc.print_(printer) logging.info("PDF created at %s" % (self.pdf_file))
def paint(self, painter, option, index): options = QStyleOptionViewItemV4(option) self.initStyleOption(options, index) style = QApplication.style( ) if options.widget is None else options.widget.style() doc = QTextDocument() doc.setHtml(options.text) options.text = "" style.drawControl(QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect(QStyle.SE_ItemViewItemText, options) # Highlighting text if item is selected if options.state & QStyle.State_Selected: # ctx.palette.setColor( # QPalette.Text, options.palette.color(QPalette.Active, QPalette.HighlightedText) # ) # painter.setBrush( options.palette.color( QPalette.Active, QPalette.Highlight ) ) # painter.setBrush( QColor( '#c1f48b' ) ) painter.setBrush(QColor(0, 180, 0, 30)) painter.setPen(Qt.NoPen) painter.drawRect(textRect) elif options.state & QStyle.State_MouseOver: # painter.setBrush( QColor( '#faffb8' ) ) # painter.setPen( Qt.NoPen ) # painter.drawRect( textRect ) painter.setBrush(QColor(0, 255, 0, 10)) painter.setPen(Qt.NoPen) painter.drawRect(textRect) else: painter.setPen(QColor(0, 0, 0, 10)) painter.drawLine(textRect.bottomLeft(), textRect.bottomRight()) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def paint(self, painter, option, index): options = QStyleOptionViewItemV4(option) self.initStyleOption(options,index) style = QApplication.style() if options.widget is None else options.widget.style() doc = QTextDocument() doc.setHtml(options.text) options.text = "" style.drawControl( QStyle.CE_ItemViewItem, options, painter) ctx = QAbstractTextDocumentLayout.PaintContext() textRect = style.subElementRect( QStyle.SE_ItemViewItemText, options ) # Highlighting text if item is selected if options.state & QStyle.State_Selected : # ctx.palette.setColor( # QPalette.Text, options.palette.color(QPalette.Active, QPalette.HighlightedText) # ) # painter.setBrush( options.palette.color( QPalette.Active, QPalette.Highlight ) ) # painter.setBrush( QColor( '#c1f48b' ) ) painter.setBrush( QColor( 0,180,0,30 ) ) painter.setPen( Qt.NoPen ) painter.drawRect( textRect ) elif options.state & QStyle.State_MouseOver : # painter.setBrush( QColor( '#faffb8' ) ) # painter.setPen( Qt.NoPen ) # painter.drawRect( textRect ) painter.setBrush( QColor( 0,255,0,10 ) ) painter.setPen( Qt.NoPen ) painter.drawRect( textRect ) else: painter.setPen( QColor( 0,0,0,10 ) ) painter.drawLine( textRect.bottomLeft(), textRect.bottomRight() ) painter.save() painter.translate(textRect.topLeft()) painter.setClipRect(textRect.translated(-textRect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore()
def paint(self, painter, option, index): text = index.model().data(index, Qt.DisplayRole).toString() palette = QApplication.palette() document = QTextDocument() document.setDefaultFont(option.font) if option.state & QStyle.State_Selected: document.setHtml( QString("<font color=%1>%2</font>").arg( palette.highlightedText().color().name()).arg(text)) else: document.setHtml(text) painter.save() color = (palette.highlight().color() if option.state & QStyle.State_Selected else QColor(index.model().data( index, Qt.BackgroundColorRole))) painter.fillRect(option.rect, color) painter.translate(option.rect.x(), option.rect.y()) document.drawContents(painter) painter.restore()
def sizeHint(self, option1, index): # option.rect is a zero rect width = self.parent().columnWidth(index.column()) if index.data(Qt.DisplayRole).type() == QMetaType.Double: return QSize(width, 18) option = QStyleOptionViewItemV4(option1) self.initStyleOption(option, index) if not option.text: iconSize = option.icon.actualSize(QSize(32, 32)) return QSize(32, max(32, iconSize.height() + 4)) doc = QTextDocument() doc.setHtml(option.text) doc.setTextWidth(self._preferredMessageWidth(width)) return QSize(doc.idealWidth(), max(32, doc.size().height() + 4))
def _displayMessage(self, otherID, msgHTML, msgTime, msgDict): try: recvTime = time() chatWindow = self.openChat(otherID, False) chatWindow.getChatWidget().addOtherMessage(msgHTML, msgTime, recvTime) self._messagesHandler.receivedSuccessfully(otherID, msgHTML, msgTime, msgDict, recvTime) except: excType, excValue, _tb = sys.exc_info() errorMsg = u"Error processing message (%s: %s)" % (unicode(excType.__name__), unicode(excValue)) self._messagesHandler.errorReceivingMessage(otherID, msgDict, errorMsg) if not chatWindow.isActiveWindow(): from PyQt4.QtGui import QTextDocument doc = QTextDocument() doc.setHtml(msgHTML) displayNotification(chatWindow.getChatWidget().getOtherName(), convert_string(doc.toPlainText()), self.logger, chatWindow.getChatWidget().getOtherIconPath())
def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.setupUi(self) self.btnHelp = self.buttonBox.button(QDialogButtonBox.Help) cfg = ConfigParser.SafeConfigParser() cfg.read(os.path.join(pluginPath, 'metadata.txt')) version = cfg.get('general', 'version') self.lblLogo.setPixmap( QPixmap(os.path.join(pluginPath, 'icons', 'photo2shape.png'))) self.lblVersion.setText(self.tr('Version: {}'.format(version))) doc = QTextDocument() doc.setHtml(self.getAboutText()) self.textBrowser.setDocument(doc) self.textBrowser.setOpenExternalLinks(True) self.buttonBox.helpRequested.connect(self.openHelp)
def resizeEvent( self, event ): super(VersionItemWidget,self).resizeEvent(event) # make sure we have finished initializing before we resize if ( not '_version' in self.__dict__ ): return metrics = QFontMetrics(self.font()) version = self._version # update the labels with eliding based on new spacing self.uiUserLBL.setText( metrics.elidedText( version.username(), Qt.ElideRight, self.uiUserLBL.width() ) ) # convert out any html data comments = str(version.comments()) doc = QTextDocument() doc.setHtml(comments) comments = str(doc.toPlainText()) self.uiCommentsLBL.setText( metrics.elidedText( comments.replace('\n',' '), Qt.ElideRight, self.uiCommentsLBL.width() ) )
def paint(self, painter, option, index): text = index.model().data(index, Qt.DisplayRole).toString() palette = QApplication.palette() document = QTextDocument() document.setDefaultFont(option.font) if option.state & QStyle.State_Selected: document.setHtml(QString("<font color=%1>%2</font>") .arg(palette.highlightedText().color().name()) .arg(text)) else: document.setHtml(text) painter.save() color = (palette.highlight().color() if option.state & QStyle.State_Selected else QColor(index.model().data(index, Qt.BackgroundColorRole))) painter.fillRect(option.rect, color) painter.translate(option.rect.x(), option.rect.y()) document.drawContents(painter) painter.restore()
def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.setupUi(self) self.btnHelp = self.buttonBox.button(QDialogButtonBox.Help) self.lblLogo.setPixmap( QPixmap(':/plugins/osmpoly_export/icons/osmpoly_export.png')) cfg = ConfigParser.SafeConfigParser() cfg.read(os.path.join(os.path.dirname(__file__), 'metadata.txt')) version = cfg.get('general', 'version') self.lblVersion.setText(self.tr('Version: %s') % version) self.lblName.setText(self.tr('Export OSM Poly')) doc = QTextDocument() doc.setHtml(self.getAboutText()) self.textBrowser.setDocument(doc) self.textBrowser.setOpenExternalLinks(True) self.buttonBox.helpRequested.connect(self.openHelp)
def print_document(document, verse_key, pdf = False, copies=1, skip=False): printer = QPrinter(QPrinter.HighResolution) if not pdf: printer.setOutputFormat(QPrinter.NativeFormat) else: printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(ROOT + 'verse.pdf') printer.setPaperSize(QPrinter.A4) printer.setCopyCount(copies) printer.setPageMargins(10, 10, 10, 10, QPrinter.Millimeter) doc = QTextDocument() doc.setHtml(concatenate_pages(document, verse_key, skip)) dialog = QPrintPreviewDialog(printer) dialog.setWindowFlags(Qt.Window) dialog.setWindowTitle('Print preview: parse results') def preview(): doc.print_(printer) dialog.paintRequested.connect(preview) dialog.exec_()
def resizeEvent(self, event): super(VersionItemWidget, self).resizeEvent(event) # make sure we have finished initializing before we resize if (not '_version' in self.__dict__): return metrics = QFontMetrics(self.font()) version = self._version # update the labels with eliding based on new spacing self.uiUserLBL.setText( metrics.elidedText(version.username(), Qt.ElideRight, self.uiUserLBL.width())) # convert out any html data comments = str(version.comments()) doc = QTextDocument() doc.setHtml(comments) comments = str(doc.toPlainText()) self.uiCommentsLBL.setText( metrics.elidedText(comments.replace('\n', ' '), Qt.ElideRight, self.uiCommentsLBL.width()))
# coding: utf-8 from PyQt4.QtCore import QSizeF from PyQt4.QtGui import QColor, QTextDocument from qgis.core import QgsPoint from qgis.gui import QgsTextAnnotationItem from qgis.utils import iface canvas = iface.mapCanvas() text_annotation_item = QgsTextAnnotationItem(canvas) X, Y = float(3), float(45) point = QgsPoint(X, Y) text_annotation_item.setMapPosition(point) text_annotation_item.setFrameSize(QSizeF(300, 200)) text_annotation_item.setFrameColor(QColor(0, 255, 0)) text_annotation_item.setFrameBackgroundColor(QColor(128, 128, 128)) text_document = QTextDocument() html_content = "<b>New annotation</b>" font_color, font_family, font_size = "#123456", "Times New Roman", 16 text_document.setHtml('<font style="color:' + font_color + "; font-family:" + font_family + "; font-size: " + str(font_size) + 'px">' + html_content + "</font>") text_annotation_item.setDocument(text_document) canvas.refresh() # Then remove # canvas.scene().removeItem(text_annotation_item)
from PyQt4.QtGui import QTextDocument, QPrinter, QApplication import sys app = QApplication(sys.argv) doc = QTextDocument() location = "https://translate.google.cn/" html = open(location).read() doc.setHtml(html) printer = QPrinter() printer.setOutputFileName("foo.pdf") printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) printer.setPageMargins (15,15,15,15,QPrinter.Millimeter) doc.print_(printer) print ("done!")
def paint(self, painter, option, index): painter.save() cell_width = self.size.width() #if option.state & QStyle.State_Selected: # painter.fillRect(option.rect, option.palette.highlight()) #painter.drawRect(option.rect) # Draw marks before translating painter # ===================================== # Draw avatar if not self.avatar: avatar_filepath = index.data(self.AvatarRole).toPyObject() self.avatar = QPixmap(avatar_filepath) x = option.rect.left() + (self.BOX_MARGIN * 2) y = option.rect.top() + (self.BOX_MARGIN * 2) rect = QRect(x, y, self.AVATAR_SIZE, self.AVATAR_SIZE) painter.drawPixmap(rect, self.avatar) # Draw verified account icon if index.data(self.VerifiedRole).toPyObject(): rect2 = QRect(rect.right() - 11, rect.bottom() - 10, 16, 16) painter.drawPixmap(rect2, self.verified_icon) marks_margin = 0 # Favorite mark if index.data(self.FavoritedRole).toPyObject(): x = cell_width - 16 - self.BOX_MARGIN y = option.rect.top() + self.BOX_MARGIN rect = QRect(x, y, 16, 16) painter.drawPixmap(rect, self.favorite_icon) marks_margin = 16 # Draw reposted icon if index.data(self.RepeatedRole).toPyObject(): x = cell_width - 16 - self.BOX_MARGIN - marks_margin y = option.rect.top() + self.BOX_MARGIN rect = QRect(x, y, 16, 16) painter.drawPixmap(rect, self.repeated_icon) # Draw protected account icon protected_icon_margin = 0 if index.data(self.ProtectedRole).toPyObject(): x = option.rect.left( ) + self.BOX_MARGIN + self.AVATAR_SIZE + self.LEFT_MESSAGE_MARGIN y = option.rect.top() + self.BOX_MARGIN rect = QRect(x, y, 16, 16) painter.drawPixmap(rect, self.protected_icon) protected_icon_margin = 16 # ==== End of pixmap drawing ==== accumulated_height = 0 # Draw fullname fullname = self.__render_fullname(cell_width, index) x = option.rect.left() + self.BOX_MARGIN + self.AVATAR_SIZE x += self.LEFT_MESSAGE_MARGIN + protected_icon_margin y = option.rect.top() painter.translate(x, y) fullname.drawContents(painter) # Draw username username = self.__render_username(cell_width, index) painter.translate(fullname.idealWidth(), 0) username.drawContents(painter) # Draw status message x = -fullname.idealWidth() - protected_icon_margin y = fullname.size().height() + self.TOP_MESSAGE_MARGIN painter.translate(x, y) message = self.__render_status_message(cell_width, index) message.drawContents(painter) accumulated_height += y + message.size().height() # Draw reposted by x = self.BOX_MARGIN + 16 - (self.LEFT_MESSAGE_MARGIN + self.AVATAR_SIZE) y = message.size().height() + self.BOTTOM_MESSAGE_MARGIN if accumulated_height < self.AVATAR_SIZE: y += (self.AVATAR_SIZE - accumulated_height) + self.COMPLEMENT_HEIGHT painter.translate(x, y) reposted_by = index.data(self.RepostedRole).toPyObject() if reposted_by: reposted = QTextDocument() reposted.setHtml("<span style='color: #999;'>%s</span>" % reposted_by) reposted.setDefaultFont(FOOTER_FONT) reposted.setTextWidth(self.__calculate_text_width(cell_width)) reposted.drawContents(painter) # Draw reposted icon rect2 = QRect(-16, 3, 16, 16) painter.drawPixmap(rect2, self.reposted_icon) # Draw datetime datetime = index.data(self.DateRole).toPyObject() timestamp = QTextDocument() timestamp.setHtml("<span style='color: #999;'>%s</span>" % datetime) timestamp.setDefaultFont(FOOTER_FONT) timestamp.setTextWidth(self.__calculate_text_width(cell_width)) x = self.size.width() - timestamp.idealWidth() - 20 - self.BOX_MARGIN painter.translate(x, 0) timestamp.drawContents(painter) painter.resetTransform() painter.translate(0, option.rect.bottom()) line = QLine(0, 0, option.rect.width(), 0) painter.setPen(QColor(230, 230, 230)) painter.drawLine(line) painter.restore()