Example #1
1
    def paint(self, painter, option, index):
        option = QStyleOptionViewItem(option) # copy option
        self.initStyleOption(option, index)

        style = option.widget.style() if option.widget else QApplication.style()

        doc = QTextDocument()
        doc.setHtml(option.text)

        # painting item without text
        option.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, option, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        # Hilight 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, option)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)
        painter.restore()
Example #2
0
 def __init__(self, aid, agentInfo, drawingInputs):
     self.aid = aid
     self.agentInfo, self.drawingInputs = agentInfo, drawingInputs
     #
     self.prep_trajDrawing()
     self.oLabels, self.dLabels = [], []
     self.luLabels = []
     for r, (_, timeBudget, oLoc, seqLocs, dLoc) in enumerate(agentInfo):
         label = QTextDocument()
         label.setHtml("o<sup>%d</sup><sub>%d</sub>" % (self.aid, r))
         label.setDefaultFont(Task.font)
         self.oLabels.append(label)
         label = QTextDocument()
         label.setHtml("d<sup>%d</sup><sub>%d</sub>" % (self.aid, r))
         label.setDefaultFont(Task.font)
         self.dLabels.append(label)
         #
         locS = [oLoc]
         for loc in seqLocs:
             locS.append(loc)
         locS.append(dLoc)
         dist = 0.0
         for i in range(len(locS) - 1):
             dist += np.linalg.norm(locS[i] - locS[i + 1])
         label = QTextDocument()
         label.setHtml(
             "RR<sup>%d</sup><sub>%d</sub>=%.2f u<sup>%d</sup><sub>%d</sub>=%.2f"
             % (self.aid, r, dist, self.aid, r, timeBudget))
         label.setDefaultFont(Task.font)
         self.luLabels.append(label)
Example #3
0
 def __init__(self, model, parent, *args):
     super(HexItemDelegate, self).__init__(parent)
     # compute size hint for hex view
     dh = QTextDocument()
     dh.setHtml("<font color='green'>DF</font>")
     self.hex_hint = QtCore.QSize(dh.idealWidth()-dh.documentMargin(), 22)
     # compute size hint for char view
     dc = QTextDocument()
     dc.setHtml("W")
     self.char_hint = QtCore.QSize(dc.idealWidth()-dc.documentMargin(), 22)
     self._model = model
Example #4
0
 def __init__(self, tid, taskInfo, drawingInputs):
     self.tid = tid
     #
     self.plabel, self.dlabel = QTextDocument(), QTextDocument()
     self.plabel.setHtml("%d<sup>+</sup>" % self.tid)
     self.dlabel.setHtml("%d<sup>-</sup>" % self.tid)
     self.plabel.setDefaultFont(Task.font)
     self.dlabel.setDefaultFont(Task.font)
     #
     pLocXY, dLocXY, pTW_Xs, dTW_Xs, self.coX4GC, self.oriY_GC, self.yUnit = drawingInputs
     self.ppX, self.ppY = pLocXY
     self.dpX, self.dpY = dLocXY
     self.pTW_rect = self.get_twRect(pTW_Xs, isPickupTW=True)
     self.dTW_rect = self.get_twRect(dTW_Xs, isPickupTW=False)
Example #5
0
 def slot_print(self):
     printer = QPrintDialog(self.document_prt)
     if printer.exec() != QDialog.Accepted:
         return
     doc = QTextDocument()
     doc.setPlainText(self.editor.toPlainText())
     doc.print(self.document_prt)
Example #6
0
def stamp_image(image, expression_str, position, feature):
    painter = QPainter(image)
    data = roam.api.utils.replace_expression_placeholders(expression_str, feature)
    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
Example #7
0
 def handlePaintRequest(self, printer):
     # find empty cells
     for row in range(self.tableView.rowCount()):
         for column in range(self.tableView.columnCount()):
             myitem = self.tableView.item(row, column)
             if myitem is None:
                 item = QTableWidgetItem("")
                 self.tableView.setItem(row, column, item)
     printer.setDocName(self.fname)
     document = QTextDocument()
     cursor = QTextCursor(document)
     model = self.tableView.model()
     tableFormat = QTextTableFormat()
     tableFormat.setBorder(0.2)
     tableFormat.setBorderStyle(3)
     tableFormat.setCellSpacing(0)
     tableFormat.setTopMargin(0)
     tableFormat.setCellPadding(4)
     table = cursor.insertTable(model.rowCount(), model.columnCount(),
                                tableFormat)
     for row in range(table.rows()):
         for column in range(table.columns()):
             cursor.insertText(self.tableView.item(row, column).text())
             cursor.movePosition(QTextCursor.NextCell)
     document.print_(printer)
Example #8
0
    def handlePaintRequest(self,printer):
        """
            This is the backbone main function that handles all the 
            print functions PrintPreview and PrintCsv .
            This handles all the required operations like bolding the header labels
            and all the other things like moving the cursor for each cell 
            row and column wise and finally printing to document.
        :param printer: 
        :return: 
        """
        document = QTextDocument()
        cursor = QTextCursor(document)
        table = cursor.insertTable(self.tableWidget.rowCount(), self.tableWidget.columnCount())
        fm = QTextCharFormat()
        font = QFont()
        font.setBold(True)
        font.setUnderline(True)
        fm.setFont(font)
        for i in range(self.tableWidget.columnCount()):
            col = self.tableWidget.horizontalHeaderItem(i).text()
            if col is not None:
                cursor.insertText(col,fm)
            cursor.movePosition(QTextCursor.NextCell)
        for row in range(self.tableWidget.rowCount()):
            for col in range(self.tableWidget.columnCount()):
                w = self.tableWidget.cellWidget(row, col)
                it = self.tableWidget.item(row, col)
                if w is not None:
                    cursor.insertText(self.get_text_from_widget(w))
                elif it is not None:
                    cursor.insertText(it.text())
                cursor.movePosition(QTextCursor.NextCell)

        document.print_(printer)
Example #9
0
    def printReciept(self, htmltext):
        dialog = QPrintDialog(self.printer, self)
        if dialog.exec_():
            document = QTextDocument()
            # print(self.printer.logicalDpiX())
            # print(self.printer.logicalDpiX() * (210 / 25.4))
            # print(self.printer.logicalDpiY())
            # print(self.printer.logicalDpiY() * (297 / 25.4))
            #A4
            # document.setPageSize(QSizeF(self.printer.logicalDpiX() * (210 / 25.4),self.printer.logicalDpiY() * (297 / 25.4)));
            #小票
            qsizeF = QSizeF(self.printer.logicalDpiX() * (257 / 25.4),
                            self.printer.logicalDpiY() * (125 / 25.4))
            # qsizeF = QSizeF(self.printer.logicalDpiX() * (215.90 / 25.4), self.printer.logicalDpiY() * (127.00 / 25.4));
            # qsizeF = QSizeF(self.printer.logicalDpiY() * (125 / 25.4),self.printer.logicalDpiX() * (257 / 25.4));
            self.printer.setPageSize(QPrinter.Custom)
            self.printer.setPaperName("小票2")
            paperSize = QSizeF(257, 125)
            self.printer.setPaperSize(paperSize, QPrinter.Millimeter)
            # self.printer.setPageSizeMM(qsizeF)

            document.setPageSize(qsizeF)
            # font = QFont();
            # font.setPointSize(6)
            # document.setDefaultFont(font);
            document.setHtml(htmltext)
            document.print_(self.printer)
Example #10
0
    def __init__(self, parentView: QTableView):
        QStyledItemDelegate.__init__(self, parentView)

        parentView.setMouseTracking(True)
        self.doc_hovered_item = QTextDocument(self)
        self.doc_hovered_item.setDocumentMargin(0)
        self.doc_not_hovered = QTextDocument(self)
        self.doc_not_hovered.setDocumentMargin(0)
        self.last_hovered_pos = QPoint(0, 0)
        self.ctx_mnu = QMenu()
        self.last_link = None
        self.last_text = None
        self.action_copy_link = self.ctx_mnu.addAction("Copy Link Location")
        self.action_copy_link.triggered.connect(self.on_action_copy_link_triggered)
        self.action_copy_text = self.ctx_mnu.addAction("Copy text")
        self.action_copy_text.triggered.connect(self.on_action_copy_text_triggered)
Example #11
0
    def __init__(self, treeViewRef, allActions, parent=None):
        """Initialize the list view.

        Arguments:
            treeViewRef -- a ref to the tree view for data
            allActions -- a dictionary of control actions for popup menus
            parent -- the parent main window
        """
        super().__init__(parent)
        self.structure = treeViewRef.model().treeStructure
        self.selectionModel = treeViewRef.selectionModel()
        self.treeModel = treeViewRef.model()
        self.allActions = allActions
        self.menu = None
        self.noMouseSelectMode = False
        self.mouseFocusNoEditMode = False
        self.prevSelSpot = None   # temp, to check for edit at mouse release
        self.drivingSelectionChange = False
        self.conditionalFilter = None
        self.messageLabel = None
        self.filterWhat = miscdialogs.FindScope.fullData
        self.filterHow = miscdialogs.FindType.keyWords
        self.filterStr = ''
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setItemDelegate(TreeEditDelegate(self))
        # use mouse event for editing to avoid with multiple select
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.itemSelectionChanged.connect(self.updateSelectionModel)
        self.itemChanged.connect(self.changeTitle)
        treeFont = QTextDocument().defaultFont()
        treeFontName = globalref.miscOptions['TreeFont']
        if treeFontName:
            treeFont.fromString(treeFontName)
            self.setFont(treeFont)
Example #12
0
    def doCompile(self, filename):
        mw = mainWindow()
        root = mw.mdlOutline.rootItem

        doc = QTextDocument()
        cursor = QTextCursor(doc)

        def appendItem(item):
            if item.isFolder():

                cursor.setPosition(doc.characterCount() - 1)
                title = "<h{l}>{t}</h{l}><br>\n".format(l=str(item.level() +
                                                              1),
                                                        t=item.title())
                cursor.insertHtml(title)

                for c in item.children():
                    appendItem(c)

            else:
                text = self.formatText(item.text(), item.type())
                cursor.setPosition(doc.characterCount() - 1)
                cursor.insertHtml(text)

        for c in root.children():
            appendItem(c)

        dw = QTextDocumentWriter(filename, "odt")
        dw.write(doc)
Example #13
0
 def dropEvent(self, e):
     _mime = e.mimeData()
     if _mime.hasUrls():
         url_list = _mime.urls()
         #
         local_urls = list(filter(lambda x: x.isLocalFile(), url_list))
         if len(local_urls) > 0:
             ret = mdm.saveUrls(local_urls)
             ret = ["[file]({})".format(_path) for _path in ret]
             _text = '\n'.join(ret)
             self.insertPlainText(_text)
             pass
         #
         web_urls = list(filter(lambda x: not x.isLocalFile(), url_list))
         if len(web_urls) > 0:
             for _url in url_list:
                 _text = '[url]({url})\n'.format(url=_url.toString())
                 self.insertPlainText(_text)
             pass
         pass
     elif _mime.hasHtml():
         _doc = QTextDocument()
         _doc.setHtml(_mime.html())
         _text = _doc.toPlainText()
         self.insertPlainText(_text)
         pass
     elif _mime.hasText():
         _text = _mime.text().strip()
         self.insertPlainText(_text)
         pass
     self.textChangedEvent()
     self.showCaret(force=True)
     self.setFocus()
     pass
Example #14
0
    def printPreview(self, obj, data):
        from PyQt5.QtPrintSupport import QPrinter, QPrintPreviewDialog
        from PyQt5.QtGui import QTextDocument, QTextCursor, QTextTableFormat, QTextFrameFormat  #, QFont
        import time

        self.printer = QPrinter()
        self.printer.setPageSize(QPrinter.A4)
        self.printer.setOrientation(QPrinter.Landscape)
        self.printer.setFullPage(True)
        self.printer.setPageMargins(2, 2, 2, 2, QPrinter.Millimeter)
        #self.printer.setFont(QFont("times",22))

        dialog = QPrintPreviewDialog(self.printer)
        #dialog.showFullScreen()

        document = QTextDocument()

        #document.setHtml("<html><head></head><body></body></html>")
        document.setHtml("")
        cursor = QTextCursor(document)

        # Titolo
        cursor.insertHtml("<h2 align=center>%s</h2>" % obj['title'])
        cursor.insertText("\n")
        # Data
        cursor.insertHtml("<h5 align=left>%s</h5>" % time.strftime("%d/%m/%Y"))
        cursor.insertText("\n")

        # Table
        tableFormat = QTextTableFormat()
        tableFormat.setCellPadding(2)
        tableFormat.setCellSpacing(3)
        #tableFormat.setBorderStyle(QTextFrameFormat.BorderStyle_Ridge)
        tableFormat.setBorder(0)

        cursor.insertTable(len(data) + 2, len(obj['col_name']), tableFormat)

        # Intestazioni
        for table_title in obj['col_name']:
            cursor.insertHtml('<font size="4" color="blue"><b>%s</b></font>' %
                              table_title)
            cursor.movePosition(QTextCursor.NextCell)

        # Riga bianca
        for table_title in obj['col_name']:
            cursor.insertText(' ')
            cursor.movePosition(QTextCursor.NextCell)

        # Dati Tabella
        for r in data:
            for k in obj['col_order']:
                v = r[k]
                if v is not None:
                    #cursor.insertText(str(v))
                    cursor.insertHtml('<font size="4">%s</font>' % v)
                    cursor.movePosition(QTextCursor.NextCell)

        dialog.paintRequested.connect(document.print_)
        dialog.setFixedSize(1500, 1050)
        dialog.exec_()
Example #15
0
    def setDocHeight(self, paintDevice, width, printFont, replaceDoc=False):
        """Set the height of this item for use in printer output.

        Creates an output document if not already created.
        Arguments:
            paintDevice -- the printer or other device for settings
            width -- the width available for the output text
            printFont -- the default font for the document
            replaceDoc -- if true, re-create the text document
        """
        if not self.doc or replaceDoc:
            self.doc = QTextDocument()
            lines = '\n'.join(self.textLines)
            if lines.endswith('<br />'):
                # remove trailing <br /> tag to avoid excess space
                lines = lines[:-6]
            self.doc.setHtml(lines)
            self.doc.setDefaultFont(printFont)
            frameFormat = self.doc.rootFrame().frameFormat()
            frameFormat.setBorder(0)
            frameFormat.setMargin(0)
            frameFormat.setPadding(0)
            self.doc.rootFrame().setFrameFormat(frameFormat)
        layout = self.doc.documentLayout()
        layout.setPaintDevice(paintDevice)
        self.doc.setTextWidth(width)
        self.height = layout.documentSize().height()
Example #16
0
def pixmap(cursor, num_lines=6, scale=0.8):
    """Return a QPixmap displaying the selected lines of the document.
    
    If the cursor has no selection, num_lines are drawn.
    
    By default the text is drawn 0.8 * the normal font size. You can change
    that by supplying the scale parameter.
    
    """
    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() * scale)
    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))
    return pix
Example #17
0
    def paint(self, painter, option, index):
        self.initStyleOption(option, index)

        style = QApplication.style()

        doc = QTextDocument()
        if index.column() in (NetworkTableModel.columns_types.index('address'),
                              NetworkTableModel.columns_types.index('port'),
                              NetworkTableModel.columns_types.index('api')):
            doc.setHtml(option.text)
        else:
            doc.setPlainText(option.text)

        option.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, option, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()

        text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
        painter.save()
        painter.translate(text_rect.topLeft())
        painter.setClipRect(text_rect.translated(-text_rect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Example #18
0
 def getHeightHint(self, label_ref, pos):
     _text = ''
     if label_ref.text():
         _doc = QTextDocument()
         _doc.setHtml(label_ref.text())
         _text = _doc.toPlainText()
         fm = QFontMetrics(label_ref.font())
         if label_ref.type == 'item_hint':
             fm_rect = QRect(*CFG.SIZE_ITEM_FULL())
             _height = fm.boundingRect(fm_rect, Qt.TextWordWrap,
                                       _text).size().height()
             size = QSize(_height, _height)
         else:
             fm_rect = QRect(
                 *CFG.SIZE_ITEM_FULL()) if not self.draw_image else QRect(
                     *CFG.SIZE_ITEM_SIDE())
             _height = fm.boundingRect(fm_rect, Qt.TextWordWrap,
                                       _text).size().height()
             size = QSize(0, _height)
         pass
     else:
         _height = min(
             label_ref.pixmap().height() + CFG.SIZE_IMG_ONLY_HEIGHT(self),
             CFG.SIZE_HISTORY_ITEM()[1])
         size = QSize(_height, 0)
         pass
     return size
Example #19
0
 def button_out_alarm(self):
     doc = QTextDocument()
     doc.setHtml(self.out_alarm_label.text())
     if doc.toPlainText() == 'Active':
         self.mqttc.publish('outdoor_alarm', '0')
     else:
         self.mqttc.publish('outdoor_alarm', '01')
 def handlePaintRequest(self, printer):
     printer.setDocName(self.fname)
     document = QTextDocument()
     cursor = QTextCursor(document)
     model = self.tableView.model()
     tableFormat = QTextTableFormat()
     tableFormat.setBorder(0.2)
     tableFormat.setBorderStyle(3)
     tableFormat.setCellSpacing(0)
     tableFormat.setTopMargin(0)
     tableFormat.setCellPadding(4)
     table = cursor.insertTable(model.rowCount() + 1, model.columnCount(),
                                tableFormat)
     model = self.tableView.model()
     ### get headers
     myheaders = []
     for i in range(0, model.columnCount()):
         myheader = model.headerData(i, Qt.Horizontal)
         cursor.insertText(str(myheader))
         cursor.movePosition(QTextCursor.NextCell)
     ### get cells
     for row in range(0, model.rowCount()):
         for col in range(0, model.columnCount()):
             index = model.index(row, col)
             cursor.insertText(str(index.data()))
             cursor.movePosition(QTextCursor.NextCell)
     document.print_(printer)
Example #21
0
    def setupUi(self):
        Ui_TransactionDlg.setupUi(self, self)
        self.setWindowTitle('Transaction')
        self.chb_word_wrap.setChecked(
            app_cache.get_value(CACHE_ITEM_DETAILS_WORD_WRAP, False, bool))
        self.apply_word_wrap(self.chb_word_wrap.isChecked())
        self.edt_recipients.setOpenExternalLinks(True)
        self.edt_recipients.viewport().setAutoFillBackground(False)

        if sys.platform == 'win32':
            self.base_font_size = '8'
            self.title_font_size = '12'
        elif sys.platform == 'linux':
            self.base_font_size = '8'
            self.title_font_size = '14'
        else:  # mac
            self.base_font_size = '10'
            self.title_font_size = '17'

        self.edt_raw_transaction.setStyleSheet(
            f'font: {self.base_font_size}pt "Courier New";')
        doc = QTextDocument(self)
        doc.setDocumentMargin(0)
        doc.setHtml(
            f'<span style=" font-size:{self.title_font_size}pt;white-space:nowrap">AAAAAAAAAAAAAAAAAA'
        )
        default_width = int(doc.size().width()) * 3
        default_height = int(default_width / 2)

        app_cache.restore_window_size(self,
                                      default_width=default_width,
                                      default_height=default_height)
        self.prepare_tx_view()
Example #22
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 #23
0
    def paint(self, painter, option, index):
        self.initStyleOption(option, index)

        foreground = index.data(Qt.ForegroundRole)
        font = index.data(Qt.FontRole)
        style = QApplication.style()

        doc = QTextDocument()
        if index.column() == HistoryTableModel.columns_types.index('pubkey'):
            doc.setHtml(option.text)
        else:
            doc.setPlainText(option.text)

        option.text = ""
        style.drawControl(QStyle.CE_ItemViewItem, option, painter)

        ctx = QAbstractTextDocumentLayout.PaintContext()
        if foreground:
            if foreground.isValid():
                ctx.palette.setColor(QPalette.Text, foreground)
        if font:
            doc.setDefaultFont(font)
        text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
        painter.save()
        painter.translate(text_rect.topLeft())
        painter.setClipRect(text_rect.translated(-text_rect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()
Example #24
0
def printHtml(printer):
    html = """<html>
    <head></head>
    <body>
        <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b><h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
        <h1>55555</h1><b>bold</b>
    </body>
    </html>"""

    textDocument = QTextDocument()
    textDocument.setHtml(html)
    # textDocument.print(printer)
    textDocument.print_(printer)
Example #25
0
    def get_pixmap(self, txt, hl, rect):
        """
        store pixmap cache. Switch to LRU cache if too much memory is used.
        """
        if (hl, txt) in HexItemDelegate.pixcache:
            return HexItemDelegate.pixcache[(hl, txt)]

        # FIXME use correct size? on non-hdpi screen, 15x22 real size
        pixmap = QPixmap(rect.width(), rect.height())
        if hl:
            # Carefully measured using the gimp. YMMV.
            # Used to be done using proper Qt API calls before pixmap cache was
            # introduced in revision 731562b77ece9301f61de6626432891dfc34ba91
            pixmap.fill(QColor.fromRgb(48, 140, 198))
        else:
            pixmap.fill(Qt.white)

        doc = QTextDocument()
        doc.setHtml(txt)
        painter = QPainter()
        painter.begin(pixmap)
        doc.drawContents(painter)
        painter.end()
        HexItemDelegate.pixcache[txt] = pixmap
        return pixmap
Example #26
0
    def sizeHint(self, styleOption, modelIndex):
        """Return the size of Data Edit Cells with rich text.

        Other cells return the base class size.
        Arguments:
            styleOption -- the data for styles and geometry
            modelIndex -- the index of the cell to be painted
        """
        cell = self.parent().item(modelIndex.row(), modelIndex.column())
        if isinstance(cell, DataEditCell):
            doc = cell.doc
            doc.setTextWidth(styleOption.rect.width())
            size = doc.documentLayout().documentSize().toSize()
            maxHeight = self.parent().height() * 9 // 10  # 90% of view height
            if (size.height() > maxHeight
                    and globalref.genOptions['EditorLimitHeight']):
                size.setHeight(maxHeight)
            if cell.field.numLines > 1:
                minDoc = QTextDocument('\n' * (cell.field.numLines - 1))
                minDoc.setDefaultFont(cell.doc.defaultFont())
                minHeight = (
                    minDoc.documentLayout().documentSize().toSize().height())
                if minHeight > size.height():
                    size.setHeight(minHeight)
            return size + QSize(0, 4)
        return super().sizeHint(styleOption, modelIndex)
Example #27
0
def test_highlight(pat, txt, segments):
    doc = QTextDocument(txt)
    highlighter = completiondelegate._Highlighter(doc, pat, Qt.red)
    highlighter.setFormat = mock.Mock()
    highlighter.highlightBlock(txt)
    highlighter.setFormat.assert_has_calls(
        [mock.call(s[0], s[1], mock.ANY) for s in segments])
Example #28
0
def color_json(obj):
    doc = QTextDocument()
    doc.setDefaultStyleSheet(open('stylesheet/json_style.css').read())
    if isinstance(obj, str):
        doc.setHtml(string_to_html(obj))
    else:
        doc.setHtml(json_to_html(obj))
    return doc
Example #29
0
	def textDocument(self, title, htmltext):
		td = QTextDocument()
		td.setMetaInformation(QTextDocument.DocumentTitle, title)
		if self.ss:
			td.setDefaultStyleSheet(self.ss)
		td.setHtml(htmltext)
		td.setDefaultFont(globalSettings.font)
		return td
Example #30
0
    def sizeHint(self, option, index):
        self.initStyleOption(option, index)

        doc = QTextDocument()
        doc.setHtml(option.text)
        doc.setTextWidth(option.rect.width())

        return QSize(doc.idealWidth(), max(doc.size().height(), option.decorationSize.height()))