Python PyQt5.QtGui.QTextDocument() Examples

The following are 17 code examples of PyQt5.QtGui.QTextDocument(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PyQt5.QtGui , or try the search function .
Example #1
Source File: others.py    From lanzou-gui with MIT License 6 votes vote down vote up
def heightForWidth(self, width):
        margins = self.contentsMargins()

        if width >= margins.left() + margins.right():
            document_width = width - margins.left() - margins.right()
        else:
            # If specified width can't even fit the margin, there's no space left for the document
            document_width = 0

        # Cloning the whole document only to check its size at different width seems wasteful
        # but apparently it's the only and preferred way to do this in Qt >= 4. QTextDocument does not
        # provide any means to get height for specified width (as some QWidget subclasses do).
        # Neither does QTextEdit. In Qt3 Q3TextEdit had working implementation of heightForWidth()
        # but it was allegedly just a hack and was removed.
        #
        # The performance probably won't be a problem here because the application is meant to
        # work with a lot of small notes rather than few big ones. And there's usually only one
        # editor that needs to be dynamically resized - the one having focus.
        document = self.document().clone()
        document.setTextWidth(document_width)

        return margins.top() + document.size().height() + margins.bottom() 
Example #2
Source File: test_completiondelegate.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_highlighted(qtbot):
    """Make sure highlighting works.

    Note that with Qt 5.11.3 and > 5.12.1 we need to call setPlainText *after*
    creating the highlighter for highlighting to work. Ideally, we'd test
    whether CompletionItemDelegate._get_textdoc() works properly, but testing
    that is kind of hard, so we just test it in isolation here.
    """
    doc = QTextDocument()
    completiondelegate._Highlighter(doc, 'Hello', Qt.red)
    doc.setPlainText('Hello World')

    # Needed so the highlighting actually works.
    edit = QTextEdit()
    qtbot.addWidget(edit)
    edit.setDocument(doc)

    colors = [f.foreground().color() for f in doc.allFormats()]
    assert QColor('red') in colors 
Example #3
Source File: read_epub.py    From Lector with GNU General Public License v3.0 6 votes vote down vote up
def get_chapter_content(self, chapter_file):
        this_file = self.find_file(chapter_file)
        if this_file:
            chapter_content = self.zip_file.read(this_file).decode()

            # Generate a None return for a blank chapter
            # These will be removed from the contents later
            contentDocument = QtGui.QTextDocument(None)
            contentDocument.setHtml(chapter_content)
            contentText = contentDocument.toPlainText().replace('\n', '')
            if contentText == '':
                chapter_content = None

            return chapter_content
        else:
            return 'Possible parse error: ' + chapter_file 
Example #4
Source File: masternode_details.py    From dash-masternode-tool with MIT License 6 votes vote down vote up
def get_max_left_label_width(self):
        doc = QTextDocument(self)
        doc.setDocumentMargin(0)
        doc.setDefaultFont(self.lblOwnerKey.font())
        doc.setHtml('Test')

        def get_lbl_text_width(lbl):
            nonlocal doc
            doc.setHtml(lbl.text())
            return int(doc.size().width() + 5)

        w = max(get_lbl_text_width(self.lblName),
                get_lbl_text_width(self.lblIP),
                get_lbl_text_width(self.lblCollateral),
                get_lbl_text_width(self.lblCollateralTxHash),
                get_lbl_text_width(self.lblDMNTxHash),
                get_lbl_text_width(self.lblOwnerKey),
                get_lbl_text_width(self.lblOperatorKey),
                get_lbl_text_width(self.lblVotingKey))

        return w 
Example #5
Source File: sources_dock.py    From kite with GNU General Public License v3.0 6 votes vote down vote up
def paint(self, painter, option, index):
            options = QtWidgets.QStyleOptionViewItem(option)
            self.initStyleOption(options, index)

            style = QtGui.QApplication.style() if options.widget is None\
                else options.widget.style()

            doc = QtGui.QTextDocument()
            doc.setHtml(options.text)

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

            ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()

            textRect = style.subElementRect(
                QtGui.QStyle.SE_ItemViewItemText, options, options.widget)
            painter.save()
            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
            doc.documentLayout().draw(painter, ctx)

            painter.restore() 
Example #6
Source File: transaction_dlg.py    From dash-masternode-tool with MIT License 5 votes vote down vote up
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.viewport().setAutoFillBackground(False)

        if sys.platform == 'win32':
            self.base_font_size = '11'
            self.title_font_size = '15'
        elif sys.platform == 'linux':
            self.base_font_size = '11'
            self.title_font_size = '17'
        else:  # mac
            self.base_font_size = '13'
            self.title_font_size = '20'

        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')
        self.edt_recipients.setStyle(ProxyStyleNoFocusRect())
        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 #7
Source File: sourcewindow.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def reload_java_sources(self):
        '''Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        '''

        androconf.debug("Getting sources for %s" % self.current_class)

        lines = []
        lines.append(("COMMENTS", [(
            "COMMENT", "// filename:%s\n// digest:%s\n\n" % (
                self.current_filename, self.current_digest))]))

        method_info_buff = ""
        for method in self.current_class.get_methods():
            method_info_buff += "// " + str(method) + "\n"

        lines.append(("COMMENTS", [(
            "COMMENT", method_info_buff + "\n\n")]))

        lines.extend(self.current_class.get_source_ext())

        #TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        #No need to save hightlighter. highlighBlock will automatically be called
        #because we passed the QTextDocument to QSyntaxHighlighter constructor
        if PYGMENTS:
            MyHighlighter(self.doc, lexer=JavaLexer())
        else:
            androconf.debug("Pygments is not present !") 
Example #8
Source File: others.py    From lanzou-gui with MIT License 5 votes vote down vote up
def __init__(self, parent=None):
        super(TableDelegate, self).__init__(parent)
        self.doc = QTextDocument(self) 
Example #9
Source File: ORStoolsDialog.py    From orstools-qgis-plugin with MIT License 5 votes vote down vote up
def _linetool_annotate_point(self, point, idx):
        annotation = QgsTextAnnotation()

        c = QTextDocument()
        html = "<strong>" + str(idx) + "</strong>"
        c.setHtml(html)

        annotation.setDocument(c)

        annotation.setFrameSize(QSizeF(27, 20))
        annotation.setFrameOffsetFromReferencePoint(QPointF(5, 5))
        annotation.setMapPosition(point)
        annotation.setMapPositionCrs(self.map_crs)

        return QgsMapCanvasAnnotationItem(annotation, self._iface.mapCanvas()).annotation() 
Example #10
Source File: suite.py    From mhw_armor_edit with The Unlicense 5 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        help_content = QTextDocument()
        help_content.setHtml(HELP_CONTENT)
        self.setOpenExternalLinks(True)
        self.setDocument(help_content) 
Example #11
Source File: sources_dock.py    From kite with GNU General Public License v3.0 5 votes vote down vote up
def sizeHint(self, option, index):
            options = QtWidgets.QStyleOptionViewItem(option)
            self.initStyleOption(options, index)

            doc = QtGui.QTextDocument()
            doc.setHtml(options.text)
            doc.setTextWidth(options.rect.width())

            return QtCore.QSize(doc.idealWidth(), doc.size().height()) 
Example #12
Source File: code2pdf.py    From code2pdf with MIT License 5 votes vote down vote up
def init_print(self, linenos=True, style="default"):
        app = QApplication([])  # 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, "letter": QPrinter.Letter}
        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 #13
Source File: widgets.py    From Lector with GNU General Public License v3.0 5 votes vote down vote up
def generate_position(self, is_read=False):
        total_chapters = len(self.metadata['content'])

        current_chapter = 1
        if is_read:
            current_chapter = total_chapters

        # Generate block count @ time of first read
        # Blocks are indexed from 0 up
        blocks_per_chapter = []
        total_blocks = 0

        if not self.are_we_doing_images_only:
            for i in self.metadata['content']:
                textDocument = QtGui.QTextDocument(None)
                textDocument.setHtml(i)
                block_count = textDocument.blockCount()

                blocks_per_chapter.append(block_count)
                total_blocks += block_count

        self.metadata['position'] = {
            'current_chapter': current_chapter,
            'total_chapters': total_chapters,
            'blocks_per_chapter': blocks_per_chapter,
            'total_blocks': total_blocks,
            'is_read': is_read,
            'current_block': 0,
            'cursor_position': 0} 
Example #14
Source File: test_completiondelegate.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
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 #15
Source File: sourcewindow.py    From dcc with Apache License 2.0 5 votes vote down vote up
def reload_java_sources(self):
        """Reload completely the sources by asking Androguard
           to decompile it again. Useful when:
            - an element has been renamed to propagate the info
            - the current tab is changed because we do not know what user
              did since then, so we need to propagate previous changes as well
        """

        log.debug("Getting sources for %s" % self.current_class)

        lines = [("COMMENTS", [(
            "COMMENT", "// filename:%s\n// digest:%s\n\n" % (
                self.current_filename, self.current_digest))])]

        method_info_buff = ""
        for method in self.current_class.get_methods():
            method_info_buff += "// " + str(method) + "\n"

        lines.append(("COMMENTS", [(
            "COMMENT", method_info_buff + "\n\n")]))

        lines.extend(self.current_class.get_source_ext())

        # TODO: delete doc when tab is closed? not deleted by "self" :(
        if hasattr(self, "doc"):
            del self.doc
        self.doc = SourceDocument(parent=self, lines=lines)
        self.setDocument(self.doc)

        # No need to save hightlighter. highlighBlock will automatically be called
        # because we passed the QTextDocument to QSyntaxHighlighter constructor
        MyHighlighter(self.doc, lexer=JavaLexer()) 
Example #16
Source File: angrysearch.py    From ANGRYsearch with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, parent=None):
            super().__init__()
            self.doc = Qg.QTextDocument(self) 
Example #17
Source File: visualizarImprimirExportar.py    From PyQt5 with MIT License 4 votes vote down vote up
def initUI(self):
        self.documento = QTextDocument()

      # =================== WIDGETS QPUSHBUTTON ==================

        buttonBuscar = QPushButton("Buscar usuarios", self)
        buttonBuscar.setFixedSize(426, 26)
        buttonBuscar.move(20, 20)

        buttonLimpiar = QPushButton("Limpiar tabla", self)
        buttonLimpiar.setFixedSize(140, 26)
        buttonLimpiar.move(452, 20)

      # =================== WIDGET QTREEWIDGET ===================

        self.treeWidgetUsuarios = QTreeWidget(self)

        self.treeWidgetUsuarios.setFont(QFont(self.treeWidgetUsuarios.font().family(), 10, False))
        self.treeWidgetUsuarios.setRootIsDecorated(False)
        self.treeWidgetUsuarios.setHeaderLabels(("D.N.I", "NOMBRE", "APELLIDO", "FECHA DE NACIMIENTO"))

        self.model = self.treeWidgetUsuarios.model()

        for indice, ancho in enumerate((110, 150, 150, 160), start=0):
            self.model.setHeaderData(indice, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole)
            self.treeWidgetUsuarios.setColumnWidth(indice, ancho)
        
        self.treeWidgetUsuarios.setAlternatingRowColors(True)

        self.treeWidgetUsuarios.setFixedSize(572, 300)
        self.treeWidgetUsuarios.move(20, 56)

      # =================== WIDGETS QPUSHBUTTON ==================

        buttonVistaPrevia = QPushButton("Vista previa", self)
        buttonVistaPrevia.setFixedSize(140, 26)
        buttonVistaPrevia.move(156, 364)

        buttonImprimir = QPushButton("Imprimir", self)
        buttonImprimir.setFixedSize(140, 26)
        buttonImprimir.move(304, 364)

        buttonExportarPDF = QPushButton("Exportar a PDF", self)
        buttonExportarPDF.setFixedSize(140, 26)
        buttonExportarPDF.move(452, 364)

      # =================== EVENTOS QPUSHBUTTON ==================

        buttonBuscar.clicked.connect(self.Buscar)
        buttonLimpiar.clicked.connect(self.limpiarTabla)
        
        buttonVistaPrevia.clicked.connect(self.vistaPrevia)
        buttonImprimir.clicked.connect(self.Imprimir)
        buttonExportarPDF.clicked.connect(self.exportarPDF)

  # ======================= FUNCIONES ============================