当前位置: 首页>>代码示例>>Python>>正文


Python Qt.QTextDocument类代码示例

本文整理汇总了Python中PyQt5.Qt.QTextDocument的典型用法代码示例。如果您正苦于以下问题:Python QTextDocument类的具体用法?Python QTextDocument怎么用?Python QTextDocument使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QTextDocument类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: profile

def profile():
    import sys
    from PyQt5.Qt import QTextDocument
    from calibre.gui2 import Application
    from calibre.gui2.tweak_book import set_book_locale
    from calibre.gui2.tweak_book.editor.themes import get_theme

    app = Application([])
    set_book_locale("en")
    raw = open(sys.argv[-2], "rb").read().decode("utf-8")
    doc = QTextDocument()
    doc.setPlainText(raw)
    h = HTMLHighlighter()
    theme = get_theme(tprefs["editor_theme"])
    h.apply_theme(theme)
    h.set_document(doc)
    h.join()
    import cProfile

    print("Running profile on", sys.argv[-2])
    h.rehighlight()
    cProfile.runctx("h.join()", {}, {"h": h}, sys.argv[-1])
    print("Stats saved to:", sys.argv[-1])
    del h
    del doc
    del app
开发者ID:GaryMMugford,项目名称:calibre,代码行数:26,代码来源:html.py

示例2: __init__

 def __init__(self, parent, text, hlclass):
     QTextDocument.__init__(self, parent)
     self.l = QPlainTextDocumentLayout(self)
     self.setDocumentLayout(self.l)
     self.highlighter = hlclass()
     self.highlighter.apply_theme(get_theme(tprefs['editor_theme']))
     self.highlighter.set_document(self)
     self.setPlainText(text)
开发者ID:Aliminator666,项目名称:calibre,代码行数:8,代码来源:highlight.py

示例3: copy_to_clipboard

 def copy_to_clipboard(self, *args):
     d = QTextDocument()
     d.setHtml(self.msg_label.text())
     QApplication.clipboard().setText(
             u'calibre, version %s (%s, embedded-python: %s)\n%s: %s\n\n%s' %
             (__version__, sys.platform, isfrozen,
                 unicode(self.windowTitle()), unicode(d.toPlainText()),
                 unicode(self.det_msg.toPlainText())))
     if hasattr(self, 'ctc_button'):
         self.ctc_button.setText(_('Copied'))
开发者ID:AEliu,项目名称:calibre,代码行数:10,代码来源:message_box.py

示例4: to_doc

 def to_doc(self, index, option=None):
     doc = QTextDocument()
     if option is not None and option.state & QStyle.State_Selected:
         p = option.palette
         group = p.Active if option.state & QStyle.State_Active else p.Inactive
         c = p.color(group, p.HighlightedText)
         c = "rgb(%d, %d, %d)" % c.getRgb()[:3]
         doc.setDefaultStyleSheet(" * { color: %s }" % c)
     doc.setHtml(index.data() or "")
     return doc
开发者ID:j-howell,项目名称:calibre,代码行数:10,代码来源:single_download.py

示例5: render_and_save

    def render_and_save(self):
        path = os.path.join(options.REPORTS_DIR, *(datetime.date.today().isoformat().split('-')))
        if not os.path.exists(path):
            os.makedirs(path)

        path = os.path.join(path, '{}.odt'.format(self.user))
        document = QTextDocument()
        document.setHtml(self.render())
        QTextDocumentWriter(path).write(document)

        self.client.save()
        report = db.Report(path=path, client_id=self.client.id)
        report.save()
        return report
开发者ID:aq1,项目名称:Hospital-Helper-2,代码行数:14,代码来源:report.py

示例6: createDocument

    def createDocument(self, rootFrame):

        # Create empty document
        self.document = QTextDocument()
        self.document.setUndoRedoEnabled(False)
        self.document.setIndentWidth(20)

        # Register a renderer for custom text objects
        mo = CustomObjectRenderer()
        mo.setParent(self.document)
        self.document.documentLayout().registerHandler(QTextCharFormat.UserObject+1, mo);

        self.cursor = QTextCursor(self.document)
        self.listLevel = 0
        self.paraFormat = None

        # add all root paragraphs
        for n in rootFrame.children:
            self.addNode(n)

        # Clean up the first paragraph if document is not empty
        self.cursor.movePosition(QTextCursor.Start)
        b = self.cursor.block()
        if b.length() == 1:
            cursor = QTextCursor(self.document.findBlockByLineNumber(0))
            cursor.select(QTextCursor.BlockUnderCursor)
            cursor.deleteChar()

        return self.document
开发者ID:afester,项目名称:CodeSamples,代码行数:29,代码来源:StylableTextModel.py

示例7: CcCommentsDelegate

class CcCommentsDelegate(QStyledItemDelegate):  # {{{

    '''
    Delegate for comments data.
    '''

    def __init__(self, parent):
        QStyledItemDelegate.__init__(self, parent)
        self.document = QTextDocument()

    def paint(self, painter, option, index):
        self.initStyleOption(option, index)
        style = QApplication.style() if option.widget is None \
                                                else option.widget.style()
        self.document.setHtml(option.text)
        style.drawPrimitive(QStyle.PE_PanelItemViewItem, option, painter, widget=option.widget)
        rect = style.subElementRect(QStyle.SE_ItemViewItemDecoration, option, self.parent())
        ic = option.icon
        if rect.isValid() and not ic.isNull():
            sz = ic.actualSize(option.decorationSize)
            painter.drawPixmap(rect.topLeft(), ic.pixmap(sz))
        ctx = QAbstractTextDocumentLayout.PaintContext()
        ctx.palette = option.palette
        if option.state & QStyle.State_Selected:
            ctx.palette.setColor(ctx.palette.Text, ctx.palette.color(ctx.palette.HighlightedText))
        textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option, self.parent())
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        self.document.documentLayout().draw(painter, ctx)
        painter.restore()

    def createEditor(self, parent, option, index):
        m = index.model()
        col = m.column_map[index.column()]
        if check_key_modifier(Qt.ControlModifier):
            text = ''
        else:
            text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
        editor = CommentsDialog(parent, text, column_name=m.custom_columns[col]['name'])
        d = editor.exec_()
        if d:
            m.setData(index, (editor.textbox.html), Qt.EditRole)
        return None

    def setModelData(self, editor, model, index):
        model.setData(index, (editor.textbox.html), Qt.EditRole)
开发者ID:AEliu,项目名称:calibre,代码行数:47,代码来源:delegates.py

示例8: to_doc

 def to_doc(self, index):
     data = index.data(Qt.UserRole)
     if data is None:
         html = _('<b>This shortcut no longer exists</b>')
     elif data.is_shortcut:
         shortcut = data.data
         # Shortcut
         keys = [unicode(k.toString(k.NativeText)) for k in shortcut['keys']]
         if not keys:
             keys = _('None')
         else:
             keys = ', '.join(keys)
         html = '<b>%s</b><br>%s: %s'%(shortcut['name'], _('Shortcuts'), keys)
     else:
         # Group
         html = '<h3>%s</h3>'%data.data
     doc =  QTextDocument()
     doc.setHtml(html)
     return doc
开发者ID:AtulKumar2,项目名称:calibre,代码行数:19,代码来源:keyboard.py

示例9: generatePDF

    def generatePDF(self, contenido):
        hoy = str(datetime.datetime.now().year) + str(datetime.datetime.now().month) + str(datetime.datetime.now().day) + str(datetime.datetime.now().hour) + str(datetime.datetime.now().minute) + str(datetime.datetime.now().second)

        nombrePdf = '../archivos/' + str(hoy + 'LIST') + '.pdf'

        fecha = str(datetime.datetime.now())

        html =  """
                     <table width="600">
                        <tr width="600" color="#000000">
                            <td width="80%">

                            </td>
                            <td width="20%" align="right">
                                <IMG SRC="kde1.png">
                            </td>
                        </tr>

                    </table>

                   <hr>
                    <br>
                    <p>
                        SALDOS
                    </p>
                    <br>

                  """+ contenido

        doc = QTextDocument()
        doc.setHtml(html)

        printer = QPrinter()
        printer.setOutputFileName(nombrePdf)

        printer.setOutputFormat(QPrinter.PdfFormat)
        doc.print(printer)
        printer.newPage()
        url = QUrl
        url = QUrl(nombrePdf)
        QDesktopServices.openUrl(url)
开发者ID:Zeldex,项目名称:PQt5-Stock-Venta-CuentaCorriente,代码行数:41,代码来源:pEstadisticas.py

示例10: CcCommentsDelegate

class CcCommentsDelegate(QStyledItemDelegate):  # {{{

    '''
    Delegate for comments data.
    '''

    def __init__(self, parent):
        QStyledItemDelegate.__init__(self, parent)
        self.document = QTextDocument()

    def paint(self, painter, option, index):
        self.initStyleOption(option, index)
        style = QApplication.style() if option.widget is None \
                                                else option.widget.style()
        self.document.setHtml(option.text)
        option.text = u''
        if hasattr(QStyle, 'CE_ItemViewItem'):
            style.drawControl(QStyle.CE_ItemViewItem, option, painter)
        ctx = QAbstractTextDocumentLayout.PaintContext()
        ctx.palette = option.palette  # .setColor(QPalette.Text, QColor("red"));
        if hasattr(QStyle, 'SE_ItemViewItemText'):
            textRect = style.subElementRect(QStyle.SE_ItemViewItemText, option)
            painter.save()
            painter.translate(textRect.topLeft())
            painter.setClipRect(textRect.translated(-textRect.topLeft()))
            self.document.documentLayout().draw(painter, ctx)
            painter.restore()

    def createEditor(self, parent, option, index):
        m = index.model()
        col = m.column_map[index.column()]
        text = m.db.data[index.row()][m.custom_columns[col]['rec_index']]
        editor = CommentsDialog(parent, text, column_name=m.custom_columns[col]['name'])
        d = editor.exec_()
        if d:
            m.setData(index, (editor.textbox.html), Qt.EditRole)
        return None

    def setModelData(self, editor, model, index):
        model.setData(index, (editor.textbox.html), Qt.EditRole)
开发者ID:AtulKumar2,项目名称:calibre,代码行数:40,代码来源:delegates.py

示例11: profile

def profile():
    import sys
    from PyQt5.Qt import QTextDocument
    from calibre.gui2 import Application
    from calibre.gui2.tweak_book import set_book_locale
    from calibre.gui2.tweak_book.editor.themes import get_theme
    app = Application([])
    set_book_locale('en')
    raw = open(sys.argv[-2], 'rb').read().decode('utf-8')
    doc = QTextDocument()
    doc.setPlainText(raw)
    h = Highlighter()
    theme = get_theme(tprefs['editor_theme'])
    h.apply_theme(theme)
    h.set_document(doc)
    h.join()
    import cProfile
    print ('Running profile on', sys.argv[-2])
    h.rehighlight()
    cProfile.runctx('h.join()', {}, {'h':h}, sys.argv[-1])
    print ('Stats saved to:', sys.argv[-1])
    del h
    del doc
    del app
开发者ID:davidfor,项目名称:calibre,代码行数:24,代码来源:html.py

示例12: __init__

 def __init__(self, parent):
     QStyledItemDelegate.__init__(self, parent)
     self.document = QTextDocument()
开发者ID:AEliu,项目名称:calibre,代码行数:3,代码来源:delegates.py

示例13: __init__

class DocumentFactory:
    
    def __init__(self, contentPath, formatManager):
        self.formatManager = formatManager
        self.contentPath = contentPath


    def createDocument(self, rootFrame):

        # Create empty document
        self.document = QTextDocument()
        self.document.setUndoRedoEnabled(False)
        self.document.setIndentWidth(20)

        # Register a renderer for custom text objects
        mo = CustomObjectRenderer()
        mo.setParent(self.document)
        self.document.documentLayout().registerHandler(QTextCharFormat.UserObject+1, mo);

        self.cursor = QTextCursor(self.document)
        self.listLevel = 0
        self.paraFormat = None

        # add all root paragraphs
        for n in rootFrame.children:
            self.addNode(n)

        # Clean up the first paragraph if document is not empty
        self.cursor.movePosition(QTextCursor.Start)
        b = self.cursor.block()
        if b.length() == 1:
            cursor = QTextCursor(self.document.findBlockByLineNumber(0))
            cursor.select(QTextCursor.BlockUnderCursor)
            cursor.deleteChar()

        return self.document


    def addNode(self, node):
        if type(node) == Paragraph:
            self.paraFormat = self.formatManager.getFormat(node.style)

            # NOTE: "The block char format is the format used when inserting 
            #        text at the beginning of an empty block."
            #       See also below.
            self.cursor.insertBlock(self.paraFormat.getBlockFormat(), self.paraFormat.getCharFormat())
            # self.cursor.insertFragment(QTextDocumentFragment.fromPlainText(''))

            if self.listLevel > 0:
                # TODO: use list style from list node - requires a stack, though ...
                listStyle = ('itemizedlist', 'level', str(self.listLevel))
                newList = self.cursor.createList(self.formatManager.getFormat(listStyle).getListFormat())
            for n in node.children:
                self.addNode(n)

        elif type(node) == List:
            self.listLevel += 1
            for n in node.children:
                self.addNode(n)
            self.listLevel -= 1

        elif type(node) is ImageFragment:
            imageObject = ImageObject()
            imagePath = os.path.join(self.contentPath, node.image)
            imageObject.setName(imagePath)

            imageObjectFormat = QTextCharFormat()
            imageObjectFormat.setObjectType(QTextFormat.UserObject + 1)
            imageObjectFormat.setProperty(QTextFormat.UserProperty + 1, imageObject)
            self.cursor.insertText('\ufffc', imageObjectFormat);

        elif type(node) is MathFragment:
            mathFormula = MathFormulaObject()
            mathFormula.setFormula(node.text)
            mathFormula.image = node.image #  renderFormula()

            mathObjectFormat = QTextCharFormat()
            mathObjectFormat.setObjectType(QTextFormat.UserObject + 1)
            mathObjectFormat.setVerticalAlignment(QTextCharFormat.AlignMiddle)
            mathObjectFormat.setProperty(QTextFormat.UserProperty + 1, mathFormula)
            self.cursor.insertText('\ufffc', mathObjectFormat);
        elif type(node) is TextFragment:
            text = node.text.replace('\n', '\u2028')
            if node.href is not None:
                fmt = self.formatManager.getFormat(('link', None, None))   # TODO!
                charFmt = fmt.getCharFormat()
                charFmt.setAnchorHref(node.href)
                self.cursor.insertText(text, charFmt)
            else:
                # "The block char format is the format used when inserting text at the beginning of an empty block.
                # Hence, the block char format is only useful for the first fragment -
                # once a fragment is inserted with a different style, and afterwards
                # another fragment is inserted with no specific style, we need to reset
                # the char format to the block's char format explicitly!
    
                if node.style is not None:
                    fmt = self.formatManager.getFormat(node.style)
                else:
                    fmt = self.paraFormat

#.........这里部分代码省略.........
开发者ID:afester,项目名称:CodeSamples,代码行数:101,代码来源:StylableTextModel.py

示例14: to_doc

 def to_doc(self, index):
     doc = QTextDocument()
     doc.setHtml(index.data())
     return doc
开发者ID:GaryMMugford,项目名称:calibre,代码行数:4,代码来源:shortcuts.py

示例15: generateList

    def generateList(self):
        hoy = str(datetime.datetime.now().year) + str(datetime.datetime.now().month) + str(datetime.datetime.now().day) + str(datetime.datetime.now().hour) + str(datetime.datetime.now().minute) + str(datetime.datetime.now().second)

        nombrePdf = '../archivos/' + str(hoy + 'LIST') + '.pdf'
        listTable = ""
        for lista in self.listProducto:
            listTable += """
                                        <tr height="80">
                                            <td width="60%" align="left" >
                                            <br>""" + str(lista[1])  + """<br>
                                            </td>
                                            <td width="20%" align="center">
                                                <br> &nbsp;&nbsp;""" + str(lista[3])  + """<br>
                                            </td>
                                            <td width="20%" align="center">
                                               <br>&nbsp;&nbsp; """ + str(lista[2])  + """<br>
                                            </td>
                                        </tr>
                                   """


        fecha = str(datetime.datetime.now())
        html =  """
                     <table width="600">
                        <tr width="600" color="#000000">
                            <td width="80%">

                            </td>
                            <td width="20%" align="right">
                                <IMG SRC="kde1.png">
                            </td>
                        </tr>

                    </table>

                   <hr>
                    <br>
                    <p>
                        LISTADO DE PRODUCTOS SIN STOCK :
                    </p>
                    <br>
                    <table width="600" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;">
                      <tr  style=" background-color: gray; border-style: inset;">
                        <td width="60%"  align="center" valign="middle">
                            <b>
                            PRODUCTOS
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                                CANTIDAD MINIMA
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                            CANTIDAD
                            </b>
                        </td>
                      </tr>
                  </table>

                  <br>
                  <br>

                  <table width="600" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;">
                      """ + listTable + """
                  </table>
                    <br>
                    <br>

                    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
                    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
                    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
                    <br>

                    <hr>
                    <br>
                    <table width="600">
                        <tr>
                            <td align="right" width="100%">
                            FECHA/HORA : """+ fecha + """
                            </td>
                        </tr>
                    </table>
                   <hr>
                """

        doc = QTextDocument()
        doc.setHtml(html)

        printer = QPrinter()
        printer.setOutputFileName(nombrePdf)

        printer.setOutputFormat(QPrinter.PdfFormat)
        doc.print(printer)
        printer.newPage()
        url = QUrl
        url = QUrl(nombrePdf)
        QDesktopServices.openUrl(url)
开发者ID:Zeldex,项目名称:PQt5-Stock-Venta-CuentaCorriente,代码行数:99,代码来源:windowNotification.py


注:本文中的PyQt5.Qt.QTextDocument类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。