Example #1
0
    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()
Example #2
0
 def displayAnnotation(self, geom, message):
     ''' Display a specific message in the centroid of a specific geometry 
     '''
     centroid = geom.centroid()
     
     # clean previous annotations:
     for annotation in self.annotations:
         try:
             scene = annotation.scene()
             if scene:
                 scene.removeItem(annotation)
         except:
             # annotation can be erased by QGIS interface
             pass
     self.annotations = []
     
     # build annotation
     textDoc = QTextDocument(message)
     item = QgsTextAnnotationItem(self.iface.mapCanvas())
     item.setMapPosition(centroid.asPoint())
     item.setFrameSize(textDoc.size())
     item.setDocument(textDoc)
     item.update()
     
     # add to annotations
     self.annotations.append(item)
     
     # center in the centroid
     self.iface.mapCanvas().setCenter(centroid.asPoint())
     self.iface.mapCanvas().zoomScale(float(self.defaultZoomScale))
     self.iface.mapCanvas().refresh()
Example #3
0
    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()
Example #4
0
def htmlCopy(document, type='editor'):
    """Returns a new QTextDocument with highlighting set as HTML textcharformats."""
    data = textformats.formatData(type)
    doc = QTextDocument()
    doc.setDefaultFont(data.font)
    doc.setPlainText(document.toPlainText())
    highlight(doc, HighlightFormats(data), ly.lex.state(documentinfo.mode(document)))
    return doc
Example #5
0
 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)
Example #6
0
 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
Example #7
0
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)
Example #8
0
 def __init__(self, parent=None):
     Base.__init__(self, parent)
     self.__modestack = [Globals.root_mode]
     self.__editors = set([])
     self.filename_head = None
     self.filename_tail = None
     self.name = None
     font = QtGui.QFont()
     font.setFamily("DejaVu Sans Mono")
     self.setDefaultFont(font)
    def __init__(self, parent, dlgType):



        FlightPlanBaseDlg.__init__(self, parent)

        # self.dlgType = dlgType

        self.setObjectName("PaIlsDlg")
        self.dlgType = dlgType
        if self.dlgType == "NpaOnFix":
            self.surfaceType = SurfaceTypes.NpaOnFix
        else:
            self.surfaceType = SurfaceTypes.NpaOverheadingNavaid
        self.initParametersPan()
        self.setWindowTitle(self.surfaceType)
        self.resize(540, 600)
        QgisHelper.matchingDialogSize(self, 650, 700)
        self.surfaceList = None
        self.manualPolygon = None

        self.mapToolPan = None
        self.toolSelectByPolygon = None

        self.accepted.connect(self.closed)
        self.rejected.connect(self.closed)

        self.wptLayer = None

        self.arpFeatureArray = []
        self.currentLayer = define._canvas.currentLayer()
        self.rwyFeatureArray = []
        self.rwyEndPosition = None
        self.initAerodromeAndRwyCmb()
        
        self.socRubber = None
        self.socAnnotation = QgsTextAnnotationItem(define._canvas)
        self.socAnnotation.setDocument(QTextDocument(Captions.SOC))
        self.socAnnotation.setFrameBackgroundColor(Qt.white)
        self.socAnnotation.setFrameSize(QSizeF(30, 20))
        self.socAnnotation.setFrameColor(Qt.magenta)
        self.socAnnotation.hide()
        self.socPoint3d = None
        
        self.daRubber = None
        self.daAnnotation = QgsTextAnnotationItem(define._canvas)
        self.daAnnotation.setDocument(QTextDocument(Captions.DA))
        self.daAnnotation.setFrameBackgroundColor(Qt.white)
        self.daAnnotation.setFrameSize(QSizeF(30, 20))
        self.daAnnotation.setFrameColor(Qt.magenta)
        self.daAnnotation.hide()
        self.daPoint3d = None

        self.annotationFAWP = self.parametersPanel.pnlFafPosition.annotation
        self.annotationMAPt = self.parametersPanel.pnlMaPtPosition.annotation
Example #10
0
 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
Example #11
0
	def __getDocument(self, content):
		"""
		Returns a `QTextDocument <http://doc.qt.nokia.com/qtextdocument.html>`_ class instance
		with given content.

		:return: Document.
		:rtype: QTextDocument
		"""

		document = QTextDocument(QString(content))
		document.clearUndoRedoStacks()
		document.setModified(False)
		return document
Example #12
0
    def sizeHint(self, option, index):
        """QStyledItemDelegate.sizeHint implementation
        """
        options = QStyleOptionViewItemV4(option)
        self.initStyleOption(options, index)

        doc = QTextDocument()
        if self._font is not None:
            doc.setDefaultFont(self._font)
        doc.setDocumentMargin(1)
        #  bad long (multiline) strings processing doc.setTextWidth(options.rect.width())
        doc.setHtml(options.text)
        return QSize(doc.idealWidth(), doc.size().height())
Example #13
0
 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
Example #14
0
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)
Example #15
0
 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
Example #16
0
    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)
    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)
Example #18
0
    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()
Example #19
0
 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))
Example #20
0
def show(cursor, pos=None, num_lines=6):
    """Displays a tooltip showing part of the cursor's Document.
    
    If the cursor has a selection, those blocks are displayed.
    Otherwise, num_lines lines are displayed.
    
    If pos is not given, the global mouse position is used.
    
    """
    block = cursor.document().findBlock(cursor.selectionStart())
    c2 = QTextCursor(block)
    if cursor.hasSelection():
        c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor)
        c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
    else:
        c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines)
    
    data = textformats.formatData('editor')
    
    doc = QTextDocument()
    font = QFont(data.font)
    font.setPointSizeF(font.pointSizeF() * .8)
    doc.setDefaultFont(font)
    doc.setPlainText(c2.selection().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlighter.highlight(doc, state=tokeniter.state(block))
    size = doc.size().toSize() + QSize(8, -4)
    pix = QPixmap(size)
    pix.fill(data.baseColors['background'])
    doc.drawContents(QPainter(pix))
    label = QLabel()
    label.setPixmap(pix)
    label.setStyleSheet("QLabel { border: 1px solid #777; }")
    label.resize(size)
    widgets.customtooltip.show(label, pos)
Example #21
0
    def documentForScript(self, script=0):
        if type(script) != Script:
            script = self.libraryList[script]

        if script not in self._cachedDocuments:
            doc = QTextDocument(self)
            doc.setDocumentLayout(QPlainTextDocumentLayout(doc))
            doc.setPlainText(script.script)
            doc.setDefaultFont(QFont(self.defaultFont))
            doc.highlighter = PythonSyntaxHighlighter(doc)
            doc.modificationChanged[bool].connect(self.onModificationChanged)
            doc.setModified(False)
            self._cachedDocuments[script] = doc
        return self._cachedDocuments[script]
Example #22
0
    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
Example #23
0
    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>&nbsp;</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)
Example #24
0
    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())
Example #25
0
    def find(self, what, *args):
        """Perform a search
        arg[0] ->  QTextDocument.FindCaseSensitively
        arg[1] ->  QTextDocument.FindWholeWords
        arg[2] ->  QTextDocument.FindBackward
        arg[3] ->  QTextDocument.RegEx
        """
        print 'find called'

        # Use flags for case match
        flags = QTextDocument.FindFlags()
        if args[0] == True:
            flags = flags | QTextDocument.FindCaseSensitively
        if args[1] == True:
            flags = flags | QTextDocument.FindWholeWords
        if args[2] == True:
            flags = flags | QTextDocument.FindBackward

        cursor = self.textCursor()
        if args[3] == True:
            cursor = self.document().find(QRegExp(what), cursor, flags)
        else:
            cursor = self.document().find(what, cursor, flags)

        if not cursor.isNull():
            self.setTextCursor(cursor)
Example #26
0
    def replace(self, what, new, *args):
        """Replace the first occurence of a search
        arg[0] ->  QTextDocument.FindCaseSensitively
        arg[1] ->  QTextDocument.FindWholeWords
        arg[2] ->  QTextDocument.FindBackward
        arg[3] ->  QTextDocument.RegEx
        """
        # Use flags for case match
        flags = QTextDocument.FindFlags()
        if args[0]:
            flags = flags | QTextDocument.FindCaseSensitively
        if args[1]:
            flags = flags | QTextDocument.FindWholeWords
        if args[2]:
            flags = flags | QTextDocument.FindBackward

        # Beginning of undo block
        pcursor = self.textCursor()
        pcursor.beginEditBlock()

        cursor = self.textCursor()

        # Replace
        # self is the QTextEdit
        if args[3] == True:
            cursor = self.document().find(QRegExp(what), cursor, flags)
        else:
            cursor = self.document().find(what, cursor, flags)
        if not cursor.isNull():
            if cursor.hasSelection():
                cursor.insertText(new)

        # Mark end of undo block
        pcursor.endEditBlock()
Example #27
0
class RichTextColumnDelegate(QStyledItemDelegate):
    """enables rich text in a view"""
    label = QLabel()
    label.setIndent(5)
    label.setTextFormat(Qt.RichText)
    document = QTextDocument()

    def __init__(self, parent=None):
        super(RichTextColumnDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        """paint richtext"""
        if option.state & QStyle.State_Selected:
            role = QPalette.Highlight
        else:
            role = QPalette.AlternateBase if index.row() % 2 else QPalette.Base
        self.label.setBackgroundRole(role)
        text = index.model().data(index, Qt.DisplayRole).toString()
        self.label.setText(text)
        self.label.setFixedSize(option.rect.size())
        painter.save()
        painter.translate(option.rect.topLeft())
        self.label.render(painter)
        painter.restore()

    def sizeHint(self, option, index):
        """compute size for the final formatted richtext"""
        text = index.model().data(index).toString()
        self.document.setDefaultFont(option.font)
        self.document.setHtml(text)
        return QSize(self.document.idealWidth() + 5,
                     option.fontMetrics.height())
Example #28
0
    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())
Example #29
0
    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()))
Example #30
0
	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()
Example #31
0
 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())
Example #32
0
    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()
Example #33
0
 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
Example #34
0
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)
Example #35
0
    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)
Example #36
0
	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 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()
Example #38
0
 def __init__(self, parent=None, flags=Qt.Dialog):
     # Base class constructor.
     super(FindDialog, self).__init__(parent, flags)
     # Prepare the GUI.
     self.setupUi(self)
     # data members
     self._text = QString()
     self._findFlags = QTextDocument.FindFlags()
     self._wrappedSearch = True
     self._updateCheckBoxes()
Example #39
0
    def makeTableDocument(self):
        printer = QPrinter()
        document = QTextDocument()
        document.setDefaultStyleSheet("table {border:1px; border-color:teal}")
        document.setDefaultStyleSheet("h1, h2, h3 {color:teal}")
        document.setDocumentMargin(0.0)
        document.setPageSize(QSizeF(printer.pageRect().size()))
        header = '''
                <html>
                    <body>
                        <div style="line-height:2.5">
                            <h1>Desmond International College</h1>
                            <h2>Km4, Happiness Street, Kafanchan</h2>
                            <h2>Kaduna, Nigeria</h2>
                        </div>
                        <div>
                            <h2 style='display:block; text-align:center; word-spacing:10vw; text-transform: uppercase; margin-top:25px; margin-bottom:15px'><u>STUDENT DATA TABLE</u></h2>    
                        </div>
                    </body>
                </html>
                '''
        #print(dir(document))

        cursor = QTextCursor(document)
        rows = self.table.rowCount()
        columns = self.table.columnCount()
        cursor.insertHtml(header)
        table = cursor.insertTable(rows + 1, columns)
        formats = table.format()
        formats.setHeaderRowCount(1)
        table.setFormat(formats)
        formats = cursor.blockCharFormat()
        formats.setFontWeight(QFont.Bold)
        for column in range(columns):
            cursor.setCharFormat(formats)
            cursor.insertText(self.table.horizontalHeaderItem(column).text())
            cursor.movePosition(QTextCursor.NextCell)
        for row in range(rows):
            for column in range(columns):
                cursor.insertText(self.table.item(row, column).text())
                cursor.movePosition(QTextCursor.NextCell)

        return document
Example #40
0
 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())
Example #41
0
    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()))
Example #42
0
    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())
Example #43
0
 def setFindFlags(self, value):
     if type(value) is QTextDocument.FindFlags:
         self._findFlags = value
     else:
         self._findFlags = QTextDocument.FindFlags()
         for bit in (QTextDocument.FindBackward,
                     QTextDocument.FindCaseSensitively,
                     QTextDocument.FindWholeWords):
             if value & int(bit):
                 self._findFlags |= bit
     self._updateCheckBoxes()
 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() ) )
Example #45
0
    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
        y0 = yMap.transform(0.5 * self.item.mzmin + 0.5 * self.item.mzmax)
        h = self.text.size().height()
        painter.translate(x0, y0 - 0.5 * h)
        self.text.drawContents(painter)
Example #46
0
    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)
Example #47
0
    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)
Example #48
0
    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)
Example #49
0
    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()
Example #50
0
 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())
Example #51
0
    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()
Example #52
0
    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())
Example #53
0
 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)
Example #54
0
    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)
Example #55
0
 def find_match(self, word, flags, findNext=False):
     flags = QTextDocument.FindFlags(flags)
     if findNext:
         self.moveCursor(QTextCursor.NoMove, QTextCursor.KeepAnchor)
     else:
         self.moveCursor(QTextCursor.StartOfWord, QTextCursor.KeepAnchor)
     found = self.find(word, flags)
     if not found:
         cursor = self.textCursor()
         self.moveCursor(QTextCursor.Start)
         found = self.find(word, flags)
         if not found:
             self.setTextCursor(cursor)
Example #56
0
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_()
Example #57
0
 def slotCursorPositionChanged(self):
     """Called whenever the cursor position changes.
     
     Highlights matching characters if the cursor is at one of them.
     
     """
     cursor = self.edit().textCursor()
     block = cursor.block()
     text = block.text()
     
     # try both characters at the cursor
     col = cursor.position() - block.position()
     end = col + 1
     col = max(0, col - 1)
     for c in text[col:end]:
         if c in self.matchPairs:
             break
         col += 1
     else:
         self.clear()
         return
     
     # the cursor is at a character from matchPairs
     i = self.matchPairs.index(c)
     cursor.setPosition(block.position() + col)
     
     # find the matching character
     new = QTextCursor(cursor)
     if i & 1:
         # look backward
         match = self.matchPairs[i-1]
         flags = QTextDocument.FindBackward
     else:
         # look forward
         match = self.matchPairs[i+1]
         flags = QTextDocument.FindFlags()
         new.movePosition(QTextCursor.Right)
     
     # search, also nesting
     rx = QRegExp(QRegExp.escape(c) + '|' + QRegExp.escape(match))
     nest = 0
     while nest >= 0:
         new = cursor.document().find(rx, new, flags)
         if new.isNull():
             self.clear()
             return
         nest += 1 if new.selectedText() == c else -1
     cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
     self.highlight([cursor, new])
Example #58
0
    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()))
Example #59
0
 def _textAndFindFlags(self, backward=False):
     text = self.findComboBox.currentText()
     flags = QTextDocument.FindFlags()
     if backward:
         flags |= QTextDocument.FindBackward
     if not self.ignoreCaseCheckBox.isChecked():
         flags |= QTextDocument.FindCaseSensitively
     if self.flagsComboBox.currentIndex() == self.FULL_WORD:
         flags |= QTextDocument.FindWholeWords
     elif self.flagsComboBox.currentIndex() == self.STARTS_WITH:
         text = QRegExp("\\b%s" % text)
         caseSensitive = not self.ignoreCaseCheckBox.isChecked(
         ) and Qt.CaseSensitive or Qt.CaseInsensitive
         text.setCaseSensitivity(caseSensitive)
     return text, flags
Example #60
0
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)