コード例 #1
1
ファイル: connection.py プロジェクト: vduseev/pyqt-sql-demo
    def build_query_text_edit(self):
        # Add layouts
        query_edit_layout = QVBoxLayout(self)
        query_edit_layout.setContentsMargins(0, 0, 0, 0)
        query_control_layout = QHBoxLayout(self)
        query_control_layout.setContentsMargins(0, 0, 0, 0)

        # Execute query button
        self.query_execute_button = QPushButton(
            UI.QUERY_CONTROL_EXECUTE_BUTTON_TEXT, self)
        self.query_execute_button.clicked.connect(self.on_execute_click)
        query_control_layout.addWidget(self.query_execute_button)

        # Fetch data button
        self.query_fetch_button = QPushButton(
            UI.QUERY_CONTROL_FETCH_BUTTON_TEXT, self)
        self.query_fetch_button.clicked.connect(self.on_fetch_click)
        self.model.fetch_changed.connect(self.on_fetch_changed)
        query_control_layout.addWidget(self.query_fetch_button)

        # Commit button
        self.query_commit_button = QPushButton(
            UI.QUERY_CONTROL_COMMIT_BUTTON_TEXT, self)
        self.query_commit_button.clicked.connect(self.on_connect_click)
        query_control_layout.addWidget(self.query_commit_button)

        # Rollback button
        self.query_rollback_button = QPushButton(
            UI.QUERY_CONTROL_ROLLBACK_BUTTON_TEXT, self)
        self.query_rollback_button.clicked.connect(self.on_rollback_click)
        query_control_layout.addWidget(self.query_rollback_button)

        # Build control strip widget
        query_control = QWidget(self)
        query_control.setLayout(query_control_layout)
        query_edit_layout.addWidget(query_control)

        # Initialize query edit document for text editor
        # and use SQL Highlighter CSS styles for it.
        self.query_text_edit_document = QTextDocument(self)
        self.query_text_edit_document.setDefaultStyleSheet(
            SQLHighlighter.style())

        # Initialize query text editor using previously built
        # text edutir document.
        self.query_text_edit = QTextEdit(self)
        self.query_text_edit.setDocument(self.query_text_edit_document)
        self.query_text_edit.textChanged.connect(self.on_query_changed)
        self.query_text_edit.setText(UI.QUERY_EDITOR_DEFAULT_TEXT)
        query_edit_layout.addWidget(self.query_text_edit)

        # Connect model's connected/disconnected signals
        self.model.connected.connect(self.on_connected)
        self.model.disconnected.connect(self.on_disconnected)

        query_edit = QWidget(self)
        query_edit.setLayout(query_edit_layout)
        query_edit.sizePolicy().setVerticalPolicy(QSizePolicy.Minimum)
        return query_edit
コード例 #2
1
ファイル: widgets.py プロジェクト: romainsc/calibre
 def paint(self, painter, option, index):
     QStyledItemDelegate.paint(self, painter, option, index)
     text, positions = index.data(Qt.UserRole)
     self.initStyleOption(option, index)
     painter.save()
     painter.setFont(option.font)
     p = option.palette
     c = p.HighlightedText if option.state & QStyle.State_Selected else p.Text
     group = (p.Active if option.state & QStyle.State_Active else p.Inactive)
     c = p.color(group, c)
     painter.setClipRect(option.rect)
     if positions is None or -1 in positions:
         painter.setPen(c)
         painter.drawText(option.rect, Qt.AlignLeft | Qt.AlignVCenter | Qt.TextSingleLine, text)
     else:
         to = QTextOption()
         to.setWrapMode(to.NoWrap)
         to.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
         positions = sorted(set(positions) - {-1}, reverse=True)
         text = '<body>%s</body>' % make_highlighted_text(Results.EMPH, text, positions)
         doc = QTextDocument()
         c = 'rgb(%d, %d, %d)'%c.getRgb()[:3]
         doc.setDefaultStyleSheet(' body { color: %s }'%c)
         doc.setHtml(text)
         doc.setDefaultFont(option.font)
         doc.setDocumentMargin(0.0)
         doc.setDefaultTextOption(to)
         height = doc.size().height()
         painter.translate(option.rect.left(), option.rect.top() + (max(0, option.rect.height() - height) // 2))
         doc.drawContents(painter)
     painter.restore()
コード例 #3
0
ファイル: html.py プロジェクト: zyhong/calibre
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')
    with open(sys.argv[-2], 'rb') as f:
        raw = f.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
コード例 #4
0
ファイル: keyboard.py プロジェクト: hanagame/calibre
 def to_doc(self, index):
     data = index.data(Qt.ItemDataRole.UserRole)
     if data is None:
         html = _('<b>This shortcut no longer exists</b>')
     elif data.is_shortcut:
         shortcut = data.data
         # Shortcut
         keys = [
             unicode_type(k.toString(
                 QKeySequence.SequenceFormat.NativeText))
             for k in shortcut['keys']
         ]
         if not keys:
             keys = _('None')
         else:
             keys = ', '.join(keys)
         html = '<b>%s</b><br>%s: %s' % (prepare_string_for_xml(
             shortcut['name']), _('Shortcuts'),
                                         prepare_string_for_xml(keys))
     else:
         # Group
         html = data.data
     doc = QTextDocument()
     doc.setHtml(html)
     return doc
コード例 #5
0
    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
コード例 #6
0
ファイル: html.py プロジェクト: GaryMMugford/calibre
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
コード例 #7
0
 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)
コード例 #8
0
ファイル: highlight.py プロジェクト: Aliminator666/calibre
 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)
コード例 #9
0
    def __init__(self, config):
        super(Doc, self).__init__()
        self._text = QTextDocument()
        self._cfg = config
        self._text_edit_cursor = QTextCursor(self._text)
        self._text.setIndentWidth(self._cfg.get("TextEditor/IndentWidth", 24))

        self.set_default_font()
コード例 #10
0
 def copy_to_clipboard(self, *args):
     d = QTextDocument()
     d.setHtml(self.msg_label.text())
     QApplication.clipboard().setText(
         u'calibre, version %s (%s, isfrozen: %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'))
コード例 #11
0
    def render_and_save(self):
        path = self._get_report_path()
        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
コード例 #12
0
ファイル: single_download.py プロジェクト: j-howell/calibre
 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
コード例 #13
0
ファイル: message_box.py プロジェクト: AEliu/calibre
 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'))
コード例 #14
0
ファイル: delegates.py プロジェクト: qunxyz/calibre
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)
コード例 #15
0
ファイル: report.py プロジェクト: aq1/Hospital-Helper-2
    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
コード例 #16
0
    def search(self, text="", show_msg=True):  # impl. of interface IEditor
        find_text = self._view.search_replace.controls["search-edit"].text()
        if not show_msg and text.strip():
            find_text = text  # pragma: no cover

        flags = QTextDocument.FindFlags()
        if self._view.search_replace.controls["cs-box"].isChecked():
            flags |= QTextDocument.FindCaseSensitively

        old_cursor = self._view.text.textCursor()
        self._view.text.moveCursor(QTextCursor.Start)
        color = QColor(Qt.yellow).lighter(130)

        extra_sels = []
        while self._view.text.find(find_text, options=flags):
            extra = QTextEdit.ExtraSelection()
            extra.format.setBackground(color)
            extra.cursor = self._view.text.textCursor()
            extra_sels.append(extra)

        self._view.text.setExtraSelections(extra_sels)

        if len(extra_sels) != 0:
            txt = self.tr("Results found")
            txt = f'{txt}: {len(extra_sels)}'
            cursor = self._view.text.textCursor()
            cursor.clearSelection()
            self._view.text.setTextCursor(cursor)
        else:
            txt = self.tr("Nothing found :(")
            self._view.text.setTextCursor(old_cursor)

        if show_msg:
            self._view.show_info(txt)
コード例 #17
0
    def _replace_all(self):
        find_text = self._view.search_replace.controls["search-edit"].text()
        repl_text = self._view.search_replace.controls["replace-edit"].text()

        flags = QTextDocument.FindFlags()
        if self._view.search_replace.controls["cs-box"].isChecked():
            flags |= QTextDocument.FindCaseSensitively

        old_cursor = self._view.text.textCursor()
        self._view.text.moveCursor(QTextCursor.Start)

        cnt = 0
        while self._view.text.find(find_text, options=flags):
            cnt += 1

        self._view.text.setTextCursor(old_cursor)
        if not cnt:
            return

        txt = (self.tr("Results found: ") + str(cnt) +
               self.tr(". Replace everything ?"))
        if not yes_no(txt, self):
            return

        cnt = 0
        self._view.text.moveCursor(QTextCursor.Start)
        while self._view.text.find(find_text, options=flags):
            self._doc.replace(repl_text)
            cnt += 1

        if cnt:
            txt = self.tr("Replacements done")
            self._view.show_info(f'{txt}: {cnt}')
コード例 #18
0
ファイル: delegates.py プロジェクト: AEliu/calibre
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)
コード例 #19
0
ファイル: keyboard.py プロジェクト: liwp-stephen/calibre
 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
コード例 #20
0
ファイル: keyboard.py プロジェクト: AtulKumar2/calibre
 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
コード例 #21
0
    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)
コード例 #22
0
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)
コード例 #23
0
ファイル: delegates.py プロジェクト: AtulKumar2/calibre
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)
コード例 #24
0
 def _search(self, forward=False):
     find_text = self._view.search_replace.controls["search-edit"].text()
     txt = self.tr("End of document.")
     flags = QTextDocument.FindFlags()
     if self._view.search_replace.controls["cs-box"].isChecked():
         flags |= QTextDocument.FindCaseSensitively
     if forward:
         flags |= QTextDocument.FindBackward
         txt = self.tr("Begin of document.")
     if not self._view.text.find(find_text, options=flags):
         self._view.show_info(txt)
         return False
     return True
コード例 #25
0
ファイル: html.py プロジェクト: davidfor/calibre
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
コード例 #26
0
ファイル: single_download.py プロジェクト: lrmbsta/calibre
 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
コード例 #27
0
    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)
コード例 #28
0
    def createFactura(self, listTransaccion, subNom, idRecibo):
        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 + subNom) + '.pdf'
        listTransaccionTable = ""
        for transaccion in listTransaccion:
            listTransaccionTable += """
                                        <tr height="80">
                                            <td width="10%" align="center" >
                                            <br>""" + str(transaccion[1])  + """<br>
                                            </td>
                                            <td width="20%" >
                                                <br> &nbsp;&nbsp;""" + str(transaccion[3])  + """<br>
                                            </td>
                                            <td width="50%" >
                                               <br>&nbsp;&nbsp; """ + str(transaccion[4])  + """<br>
                                            </td>
                                            <td width="10%" align="right" >
                                              <br>  $ """ + str(transaccion[5])  + """&nbsp;&nbsp;<br>
                                            </td>
                                            <td width="10%" align="right" >
                                              <br>  $ """ + str( int(transaccion[1]) * float(transaccion[5]))  + """&nbsp;&nbsp;<br>
                                            </td>
                                        </tr>
                                   """
        nombre = ""
        apellido = ""

        if(self.tipoTransaccion == "VENTA"):
            nombre = self.cliente.getNombre()
            apellido = self.cliente.getApellido()
        elif(self.tipoTransaccion == "COMPRA"):
            nombre = self.proveedor.getNombre()
            apellido = self.proveedor.getDescripcion()


        total = self.winPrincipal.lblTotal.text()
        fecha = str(datetime.datetime.now())
        html =  """
                     <table width="600">
                        <tr width="600" color="#000000">
                            <td width="80%">
                               Perfumeria La que vende perfumes <br>
                               LABOULAYE, CORDOBA, ARGENTINA <br>
                               TEL: 0351-111111  <br>
                               MAIL: [email protected]  <br>
                            </td>
                            <td width="20%" align="right">
                                <IMG SRC="kde1.png">
                            </td>
                        </tr>

                    </table>
                _______________________________________________________________________________________________________
                    <p>
                        DATOS DEL CLIENTE:
                    </p>
                    <br>
                    <table>

                        <tr>
                            <td>
                                NOMBRE:   """+ nombre +"""  <br>
                                APELLIDO: """ + apellido + """ <br>

                            </td>
                            <td>
                            </td>
                        </tr>
                    </table>

                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <p>
                        DETALLES DE LA COMPRA:
                    </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="10%"  align="center" valign="middle">
                            <b>
                            CANT
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                                PRODUCTO
                            </b>
                        </td>
                        <td width="50%"  align="center" valign="middle">
                            <b>
                            DESCRIPCION
                            </b>
                        </td>
                        <td width="10%"  align="center" valign="middle">
                            <b>
                            PREC <br>UNIT
                            </b>
                        </td>
                        <td width="10%"  align="center" valign="middle">
                            <b>
                            PREC <br>TOT
                            </b>
                        </td>
                      </tr>
                  </table>

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

                  <table  height="350" width="600" style="border-color: gray; border-width: .4px; border-collapse: collapse;">
                      """ + listTransaccionTable + """
                  </table>
                    <br>
                    <br>
                    <table width="600" border="0.5" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;">
                        <tr >
                            <td width="90%" align="right">
                                <br>
                                TOTAL..................................................................................................................
                                <br>
                            </td>
                            <td width="10%" align="center">
                              <br> $ """ + total + """<br>
                            </td>
                        </tr>
                    </table>

                    <br>
                    <br>
                    <br>
                    <p width="600" align="center" style=" font-size: 10; " >
                    Por cualquier consulta, sobre este recibo, dirigirse al local que se encuentra ubicado en la calle
                    independencia 450. <br> O Comunicarse a los telefonos 03382-123123123 / 4231231
                    </p>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <table width="600">
                        <tr>
                            <td align="right" width="80%">
                            FECHA/HORA : """+ fecha + """
                            </td>
                            <td align="right">
                            N° : """+ str(idRecibo) +"""
                            </td>
                        </tr>
                    </table>
                    _______________________________________________________________________________________________________
                """

        doc = QTextDocument()
        doc.setHtml(html)
        #doc.setDefaultStyleSheet(style)
        printer = QPrinter()
        printer.setOutputFileName(nombrePdf)

        printer.setOutputFormat(QPrinter.PdfFormat)
        doc.print(printer)
        printer.newPage()
        url = QUrl
        url = QUrl(nombrePdf)
        QDesktopServices.openUrl(url)

        """
コード例 #29
0
    def createRecibo(self, subNom, idRecibo, total, totDeuda, totPago):
        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 + subNom) + '.pdf'
        listTransaccionTable = ""

        nombre = ""
        apellido = ""

        if (self.state == "COBRANZA"):
            nombre = self.cliente.getNombre()
            apellido = self.cliente.getApellido()
        elif (self.state == "PAGO"):
            nombre = self.proveedor.getNombre()
            apellido = self.proveedor.getDescripcion()

        totalDeuda = float(totDeuda)
        deudaString = "$  " + "{0:.2f}".format(totalDeuda)
        totalPago = float(totPago)
        pagoString = "$  +" + "{0:.2f}".format(totalPago)

        total = float(totalDeuda + totalPago)
        totalString = "{0:.2f}".format(total)
        fecha = str(datetime.datetime.now())
        html = """
                     <table width="600">
                        <tr width="600" color="#000000">
                            <td width="80%">
                               Perfumeria La que vende perfumes <br>
                               LABOULAYE, CORDOBA, ARGENTINA <br>
                               TEL: 0351-111111  <br>
                               MAIL: [email protected]  <br>
                            </td>
                            <td width="20%" align="right">
                                <IMG SRC="kde1.png">
                            </td>
                        </tr>

                    </table>
                _______________________________________________________________________________________________________
                    <p>
                        DATOS DEL CLIENTE:
                    </p>
                    <br>
                    <table>

                        <tr>
                            <td>
                                NOMBRE:   """ + nombre + """  <br>
                                APELLIDO: """ + apellido + """ <br>

                            </td>
                            <td>
                            </td>
                        </tr>
                    </table>

                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <p>
                        DETALLES DEL RECIBO:
                    </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="80%"  align="center" valign="middle">
                            <b>
                            DESCRIPCION
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                                MONTO
                            </b>
                        </td>

                      </tr>
                  </table>

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

                  <table  height="350" width="600" style="border-color: gray; border-width: .4px; border-collapse: collapse;">
                      <tr height="80">
                            <td width="80%" align="left" >
                            <br>DEUDA <br>
                            </td>
                            <td width="20%" >
                                <br> &nbsp;&nbsp; """ + str(
            deudaString) + """<br>
                            </td>

                        </tr>
                        <tr height="80">
                            <td width="80%" align="left" >
                            <br> PAGO<br>
                            </td>
                            <td width="20%" >
                                <br> &nbsp;&nbsp;""" + str(
                pagoString) + """<br>
                            </td>

                        </tr>
                  </table>
                    <br>
                    <br>
                    <table width="600" border="0.5" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;">
                        <tr >
                            <td width="90%" align="right">
                                <br>
                                TOTAL..................................................................................................................
                                <br>
                            </td>
                            <td width="10%" align="center">
                              <br> $ """ + str(totalString) + """<br>
                            </td>
                        </tr>
                    </table>

                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    <p width="600" align="center" style=" font-size: 10; " >
                    Por cualquier consulta, sobre este recibo, dirigirse al local que se encuentra ubicado en la calle
                    independencia 450. <br> O Comunicarse a los telefonos 03382-123123123 / 4231231
                    </p>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <table width="600">
                        <tr>
                            <td align="right" width="80%">
                            FECHA/HORA : """ + fecha + """
                            </td>
                            <td align="right">
                            N° : """ + str(idRecibo) + """
                            </td>
                        </tr>
                    </table>
                    _______________________________________________________________________________________________________
                """

        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)
コード例 #30
0
class Doc(QObject):

    changed_status = pyqtSignal(dict)  # for update the status bar
    changed_bold = pyqtSignal(bool)  # for update button "Bold"
    enabled_save = pyqtSignal(bool)  # for update button "Save"

    # -------------------------------------------------------------------------
    def __init__(self, config):
        super(Doc, self).__init__()
        self._text = QTextDocument()
        self._cfg = config
        self._text_edit_cursor = QTextCursor(self._text)
        self._text.setIndentWidth(self._cfg.get("TextEditor/IndentWidth", 24))

        self.set_default_font()

    # -------------------------------------------------------------------------
    @property
    def text(self):
        return self._text

    # -------------------------------------------------------------------------
    def is_modified(self):
        return self._text.isModified()

    # -------------------------------------------------------------------------
    def in_table(self):
        return bool(self._text_edit_cursor.currentTable())

    # -------------------------------------------------------------------------
    def set_default_font(self, set_modified=False):
        font_name = self._cfg.get("TextEditor/Font", "Mono", system=True)
        sz = self._cfg.get("TextEditor/FontSize", 10, system=True)
        font = QFont(font_name, sz)
        self._text.setDefaultFont(font)
        if set_modified:
            self._text.setModified(True)
            self.change(self._text_edit_cursor)

    # -------------------------------------------------------------------------
    def change(self, text_cursor: QTextCursor = None):
        """
        Called (from QTextEdit event) with changed text or position of cursor
        """
        if text_cursor:
            self._text_edit_cursor = text_cursor

        # refresh data on statusbar
        y = self._text_edit_cursor.blockNumber() + 1
        cnt = self._text.lineCount()
        x = self._text_edit_cursor.columnNumber() + 1
        chg = (self.tr("The document is not saved")
               if self._text.isModified() else "")
        xy = f"{y} : {x} [{cnt}]"
        self.changed_status.emit({"left": chg, "right": xy})
        self.enabled_save.emit(self.is_modified())

    # -------------------------------------------------------------------------
    def bold(self):
        """
        Set/unset bold font
        """
        fmt = self._text_edit_cursor.charFormat()
        typ = QFont.Normal if fmt.fontWeight() == QFont.Bold else QFont.Bold
        fmt.setFontWeight(typ)
        self._text_edit_cursor.setCharFormat(fmt)
        self.change(self._text_edit_cursor)
        self.changed_bold.emit(typ == QFont.Bold)

    # -------------------------------------------------------------------------
    def color(self, color):
        fmt = self._text_edit_cursor.charFormat()
        fmt.setForeground(QColor(color))
        self._text_edit_cursor.setCharFormat(fmt)

    # -------------------------------------------------------------------------
    def background_color(self, color):
        fmt = self._text_edit_cursor.charFormat()
        if self.in_table():
            table = self._text_edit_cursor.currentTable()
            cell = table.cellAt(self._text_edit_cursor)
            cell_format = cell.format()
            cell_format.setBackground(QColor(color))
            cell.setFormat(cell_format)
        else:
            fmt.setBackground(QColor(color))
        self._text_edit_cursor.setCharFormat(fmt)

    # -------------------------------------------------------------------------
    def font(self, font):
        fmt = self._text_edit_cursor.charFormat()
        fmt.setFont(font)
        self._text_edit_cursor.setCharFormat(fmt)

    # -------------------------------------------------------------------------
    def font_size(self, font_size):
        fmt = self._text_edit_cursor.charFormat()
        fmt.setFontPointSize(font_size)
        self._text_edit_cursor.setCharFormat(fmt)

    # -------------------------------------------------------------------------
    def hline(self):
        """
        Insert horizontal line
        """
        # Tag HR is not correctly displayed  in QTextview
        cur_char_fmt = self._text_edit_cursor.charFormat()
        cur_block_fmt = self._text_edit_cursor.blockFormat()
        if bool(self._text_edit_cursor.currentTable()):
            self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        block_fmt = QTextBlockFormat()
        block_fmt.setTopMargin(5)
        block_fmt.setBottomMargin(5)
        block_fmt.setAlignment(Qt.AlignLeft)
        block_fmt.setBackground(QBrush(QColor("#C1C1C1")))

        char_format = QTextCharFormat()
        char_format.setFont(QFont("Arial", 1))

        self._text_edit_cursor.insertBlock(block_fmt, char_format)
        self._text_edit_cursor.insertText(" ")

        self._text_edit_cursor.insertBlock(cur_block_fmt, cur_char_fmt)

        self.change(self._text_edit_cursor)

    # -------------------------------------------------------------------------
    def show_hide_hidden_char(self, show: bool):
        if show:
            # show hidden char
            option = self._text.defaultTextOption()
            option.setFlags(
                option.flags() | QTextOption.ShowTabsAndSpaces
                | QTextOption.ShowLineAndParagraphSeparators
                | QTextOption.AddSpaceForLineAndParagraphSeparators)
            self._text.setDefaultTextOption(option)
        else:
            # remove hidden char
            option = self._text.defaultTextOption()
            stas = ~QTextOption.ShowTabsAndSpaces
            slaps = ~QTextOption.ShowLineAndParagraphSeparators
            asflaps = ~QTextOption.AddSpaceForLineAndParagraphSeparators
            option.setFlags(option.flags() & stas & slaps & asflaps)
            self._text.setDefaultTextOption(option)

    # -------------------------------------------------------------------------
    def blist(self):
        self._text_edit_cursor.insertList(QTextListFormat.ListDisc)

    # -------------------------------------------------------------------------
    def nlist(self):
        self._text_edit_cursor.insertList(QTextListFormat.ListDecimal)

    # -------------------------------------------------------------------------
    def copy_format(self, fmt):
        self._text_edit_cursor.setCharFormat(fmt)

    # -------------------------------------------------------------------------
    def clear_format(self):
        txt = self._text.toPlainText()
        self._text_edit_cursor.beginEditBlock()  # ----  begin -------
        self._text_edit_cursor.select(QTextCursor.Document)
        self._text_edit_cursor.removeSelectedText()
        fmt = QTextBlockFormat()
        self._text_edit_cursor.setBlockFormat(fmt)
        self._text_edit_cursor.insertText(txt)
        self._text_edit_cursor.endEditBlock()  # ----  end ---------

    # -------------------------------------------------------------------------
    def text_align(self, horiz, vert):

        fmt = QTextBlockFormat()
        fmt.setAlignment(horiz)
        self._text_edit_cursor.mergeBlockFormat(fmt)

        if self.in_table():
            table = self._text_edit_cursor.currentTable()
            cell = table.cellAt(self._text_edit_cursor)
            cell_format = cell.format()
            cell_format.setVerticalAlignment(vert)
            cell.setFormat(cell_format)

    # -------------------------------------------------------------------------
    def insert_table(self, table_params):
        fmt = QTextTableFormat()
        fmt.setCellPadding(table_params["padding"])
        fmt.setCellSpacing(table_params["space"])
        return self._text_edit_cursor.insertTable(table_params["rows"],
                                                  table_params["cols"], fmt)

    # -------------------------------------------------------------------------
    def table(self):
        """
        Current table if cursor in table
        """
        return self._text_edit_cursor.currentTable()

    # -------------------------------------------------------------------------
    def cell(self):
        """
        Cell in current table
        """
        return self.table().cellAt(self._text_edit_cursor)

    # -------------------------------------------------------------------------
    def add_row(self):
        self.table().appendRows(1)

    # -------------------------------------------------------------------------
    def add_col(self):
        self.table().appendColumns(1)

    # -------------------------------------------------------------------------
    def del_row(self):
        self.table().removeRows(self.cell().row(), 1)

    # -------------------------------------------------------------------------
    def del_col(self):
        self.table().removeColumns(self.cell().column(), 1)

    # -------------------------------------------------------------------------
    def ins_row(self):
        self.table().insertRows(self.cell().row(), 1)

    # -------------------------------------------------------------------------
    def ins_col(self):
        self.table().insertColumns(self.cell().column(), 1)

    # -------------------------------------------------------------------------
    def merge_cells(self):
        self.table().mergeCells(self._text_edit_cursor)

    # -------------------------------------------------------------------------
    def split_cells(self):
        self.table().splitCell(self.cell().row(), self.cell().column(), 1, 1)

    # -------------------------------------------------------------------------
    def replace(self, replace_text):
        self._text_edit_cursor.insertText(replace_text)

    # -------------------------------------------------------------------------
    def ins_date(self):
        self._text_edit_cursor.insertText(
            datetime.datetime.now().strftime("%d.%m.%Y "))

    # -------------------------------------------------------------------------
    def ins_time(self):
        self._text_edit_cursor.insertText(
            datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S "))

    # -------------------------------------------------------------------------
    def in_image(self):
        return self._text_edit_cursor.charFormat().isImageFormat()

    # -------------------------------------------------------------------------
    def ins_image(self, image, fmt, width, height, insert_space=True):
        bytes_ = QByteArray()
        buffer = QBuffer(bytes_)
        buffer.open(QIODevice.WriteOnly)
        image.save(buffer, fmt)
        buffer.close()

        base64 = bytes_.toBase64().data().decode(encoding="utf-8")

        s = (f'<img width="{width}" height="{height}" '
             f'src="data:image/{fmt};base64,{base64}"')

        self._text_edit_cursor.insertHtml(s)

        if insert_space:
            self._text_edit_cursor.insertText(" ")

    # -------------------------------------------------------------------------
    @staticmethod
    def get_image(html):
        image, width, height, fmt = None, -1, -1, "png"
        if "<img" in html:
            raw = html[html.index("<img"):].split(">")[0].split('"')
            for i, r in enumerate(raw):
                if "base64" in r:
                    img_txt = r.split(",")[-1].encode(encoding="utf-8")
                    image = QPixmap()
                    image.width()
                    image.height()
                    image.loadFromData(QByteArray.fromBase64(img_txt))
                    fmt = r.split("image/")[1].split(";")[0]
                if "width" in r and i + 1 < len(raw):
                    width = int(raw[i + 1])
                if "height" in r and i + 1 < len(raw):
                    height = int(raw[i + 1])
        return image, width, height, fmt

    # -------------------------------------------------------------------------
    def save(self, save_proc):
        if self._text.isModified():
            self._text.setModified(False)
            if self._cfg.get("TextEditor/PlainText", 0):
                txt = str(self._text.toPlainText())
                if self._cfg.get("TextEditor/ReplaceTabWithSpace", 0):
                    cnt = self._cfg.get("TextEditor/CountSpaceInTab", 1)
                    txt = txt.replace("\t", " " * cnt)
                res = save_proc(txt)
            else:
                res = save_proc(str(self._text.toHtml(encoding=QByteArray())))
            if res is not None:
                self._text.setModified(True)

        self.change(self._text_edit_cursor)

    # -------------------------------------------------------------------------
    def load(self, load_proc):
        self._text.clear()
        if self._cfg.get("TextEditor/PlainText", 0):
            self._text.setPlainText(load_proc())
        else:
            self._text.setHtml(load_proc())
        self._text.setModified(False)

    # -------------------------------------------------------------------------
    def get_text(self):
        if self._cfg.get("TextEditor/PlainText", 0):
            return str(self._text.toPlainText())
        else:
            return str(self._text.toHtml(encoding=QByteArray()))

    # -------------------------------------------------------------------------
    def is_empty(self):
        return not bool(len(self._text.toPlainText().strip()))
コード例 #31
0
ファイル: delegates.py プロジェクト: AEliu/calibre
 def __init__(self, parent):
     QStyledItemDelegate.__init__(self, parent)
     self.document = QTextDocument()
コード例 #32
0
ファイル: shortcuts.py プロジェクト: GaryMMugford/calibre
 def to_doc(self, index):
     doc = QTextDocument()
     doc.setHtml(index.data())
     return doc
コード例 #33
0
ファイル: shortcuts.py プロジェクト: zwlistu/calibre
 def to_doc(self, index):
     doc = QTextDocument()
     doc.setHtml(index.data())
     return doc
コード例 #34
0
    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)
コード例 #35
0
ファイル: connection.py プロジェクト: vduseev/pyqt-sql-demo
class ConnectionWidget(QWidget):
    title_changed = pyqtSignal(QWidget, str, name="title_changed")

    def __init__(self, parent):
        super().__init__(parent)

        # Initialize anti-recursion flag during highlighting
        self.is_processing_highlighting = False

        # Initial widget title
        self.title = UI.CONNECTION_TAB_DEFAULT_TITLE

        # Initialize data model
        self.model = ConnectionModel(self)
        self.model.connected.connect(self.on_connection_changed)

        # Initialize UI
        self.init_ui()

    def init_ui(self):
        # Declare main vertical layout
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        # Initialize control toolbar
        control_bar = self.build_control_bar()
        layout.addWidget(control_bar)

        # Initialize workspace
        workspace = self.build_workspace()
        layout.addWidget(workspace)

        # Apply configured UI layout to the widget
        self.setLayout(layout)

    def build_control_bar(self):
        # Add control bar
        control_row_layout = QHBoxLayout(self)
        control_row_layout.setContentsMargins(0, 0, 0, 0)

        # DB type combo box
        db_combo_box = QComboBox(self)
        for dbname in UI.CONNECTION_STRING_SUPPORTED_DB_NAMES:
            db_combo_box.addItem(dbname)
        control_row_layout.addWidget(db_combo_box)

        # Connection string
        self.connection_line = QLineEdit(self)
        self.connection_line.setPlaceholderText(
            UI.CONNECTION_STRING_PLACEHOLDER)
        self.connection_line.setText(UI.CONNECTION_STRING_DEFAULT)
        control_row_layout.addWidget(self.connection_line)

        # Connection button
        connection_button = QPushButton(self)
        connection_button.setText(UI.QUERY_CONTROL_CONNECT_BUTTON_TEXT)
        connection_button.clicked.connect(self.on_connect_click)
        control_row_layout.addWidget(connection_button)

        # Add contol row as a first widget in a column
        control_row = QWidget(self)
        control_row.setLayout(control_row_layout)
        return control_row

    def build_workspace(self):
        # Create a splitter consisting of query edit and table view
        splitter = QSplitter(self)
        splitter.setOrientation(Qt.Vertical)
        splitter.sizePolicy().setVerticalPolicy(QSizePolicy.Maximum)

        # Initialize query edit
        query_edit = self.build_query_text_edit()

        # Disable query control buttons by default
        self.on_disconnected()
        splitter.addWidget(query_edit)

        # Initialize result desiplaying widgets
        results_widget = self.build_results_widget()
        splitter.addWidget(results_widget)
        splitter.setSizes([100, 900])
        return splitter

    def build_query_text_edit(self):
        # Add layouts
        query_edit_layout = QVBoxLayout(self)
        query_edit_layout.setContentsMargins(0, 0, 0, 0)
        query_control_layout = QHBoxLayout(self)
        query_control_layout.setContentsMargins(0, 0, 0, 0)

        # Execute query button
        self.query_execute_button = QPushButton(
            UI.QUERY_CONTROL_EXECUTE_BUTTON_TEXT, self)
        self.query_execute_button.clicked.connect(self.on_execute_click)
        query_control_layout.addWidget(self.query_execute_button)

        # Fetch data button
        self.query_fetch_button = QPushButton(
            UI.QUERY_CONTROL_FETCH_BUTTON_TEXT, self)
        self.query_fetch_button.clicked.connect(self.on_fetch_click)
        self.model.fetch_changed.connect(self.on_fetch_changed)
        query_control_layout.addWidget(self.query_fetch_button)

        # Commit button
        self.query_commit_button = QPushButton(
            UI.QUERY_CONTROL_COMMIT_BUTTON_TEXT, self)
        self.query_commit_button.clicked.connect(self.on_connect_click)
        query_control_layout.addWidget(self.query_commit_button)

        # Rollback button
        self.query_rollback_button = QPushButton(
            UI.QUERY_CONTROL_ROLLBACK_BUTTON_TEXT, self)
        self.query_rollback_button.clicked.connect(self.on_rollback_click)
        query_control_layout.addWidget(self.query_rollback_button)

        # Build control strip widget
        query_control = QWidget(self)
        query_control.setLayout(query_control_layout)
        query_edit_layout.addWidget(query_control)

        # Initialize query edit document for text editor
        # and use SQL Highlighter CSS styles for it.
        self.query_text_edit_document = QTextDocument(self)
        self.query_text_edit_document.setDefaultStyleSheet(
            SQLHighlighter.style())

        # Initialize query text editor using previously built
        # text edutir document.
        self.query_text_edit = QTextEdit(self)
        self.query_text_edit.setDocument(self.query_text_edit_document)
        self.query_text_edit.textChanged.connect(self.on_query_changed)
        self.query_text_edit.setText(UI.QUERY_EDITOR_DEFAULT_TEXT)
        query_edit_layout.addWidget(self.query_text_edit)

        # Connect model's connected/disconnected signals
        self.model.connected.connect(self.on_connected)
        self.model.disconnected.connect(self.on_disconnected)

        query_edit = QWidget(self)
        query_edit.setLayout(query_edit_layout)
        query_edit.sizePolicy().setVerticalPolicy(QSizePolicy.Minimum)
        return query_edit

    def build_results_widget(self):
        # Initialize QTabWidget to display table view and log
        # in differnt unclosable tabs
        results_widget = QTabWidget(self)
        results_widget.setTabsClosable(False)

        # Add table view
        table_view = QTableView(self)
        table_view.setModel(self.model)
        table_view.sizePolicy().setVerticalPolicy(QSizePolicy.MinimumExpanding)
        results_widget.addTab(table_view, UI.QUERY_RESULTS_DATA_TAB_TEXT)

        # Att log view
        log = QTextEdit(self)
        log.setReadOnly(True)
        self.model.executed.connect(log.append)
        results_widget.addTab(log, UI.QUERY_RESULTS_EVENTS_TAB_TEXT)
        return results_widget

    def on_query_changed(self):
        """Process query edits by user"""
        if self.is_processing_highlighting:
            # If we caused the invokation of this slot by set highlighted
            # HTML text into query editor, then ignore this call and
            # mark highlighting processing as finished.
            self.is_processing_highlighting = False
        else:
            # If changes to text were made by user, mark beginning of
            # highlighting process
            self.is_processing_highlighting = True
            # Get plain text query and highlight it
            query_text = self.query_text_edit.toPlainText()
            highlighted_query_text = SQLHighlighter.highlight(query_text)

            # After we set highlighted HTML back to QTextEdit form
            # the cursor will jump to the end of the text.
            # To avoid that we remember the current position of the cursor.
            current_cursor = self.query_text_edit.textCursor()
            current_cursor_position = current_cursor.position()
            # Set highlighted text back to editor which will cause the
            # cursor to jump to the end of the text.
            self.query_text_edit_document.setHtml(highlighted_query_text)
            # Return cursor back to the old position
            current_cursor.setPosition(current_cursor_position)
            self.query_text_edit.setTextCursor(current_cursor)

    def on_connect_click(self):
        with ErrorHandler():
            connection_string = self.connection_line.text()
            self.model.connect(connection_string)
            logging.info(f"Connected: {connection_string}")

    def on_execute_click(self):
        with ErrorHandler():
            query = self.query_text_edit.toPlainText()
            self.model.execute(query)
            logging.info(f"Executed: {query}")

    def on_fetch_click(self):
        with ErrorHandler():
            self.model.fetch_more()
            logging.info("Fetch more")

    def on_rollback_click(self):
        with ErrorHandler():
            self.model.rollback()
            logging.info("Rollback")

    def on_connected(self):
        self.query_commit_button.setEnabled(True)
        self.query_execute_button.setEnabled(True)
        self.query_fetch_button.setEnabled(False)
        self.query_rollback_button.setEnabled(True)
        self.query_text_edit.setEnabled(True)

    def on_disconnected(self):
        self.query_commit_button.setEnabled(False)
        self.query_execute_button.setEnabled(False)
        self.query_fetch_button.setEnabled(False)
        self.query_rollback_button.setEnabled(False)
        self.query_text_edit.setEnabled(False)

    def on_fetch_changed(self, state):
        self.query_fetch_button.setEnabled(state)

    def on_connection_changed(self, name):
        self.title_changed.emit(self, name)
コード例 #36
0
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

                self.cursor.insertText(text, fmt.getCharFormat())
コード例 #37
0
    def generarRecibo(self, listDetail, subName, id, header):
        """

        @param listDetail: lista de detalles
        @param subName: Sub-nombre para generar el PDF
        @param id: Id del recibo
        """
        self.nombrePdf = '../archivos/' + str(self.hoy + subName) + '.pdf'
        listDetalHtml = self.generateTableTransaction(listDetail, header)

        nombre = ""
        apellido = ""

        if (self.tipoTransaccion == "VENTA"):
            nombre = self.cliente.getNombre()
            apellido = self.cliente.getApellido()
        elif (self.tipoTransaccion == "COMPRA"):
            nombre = self.proveedor.getNombre()
            apellido = self.proveedor.getDescripcion()

        total = self.winPrincipal.lblTotal.text()
        fecha = str(datetime.datetime.now())
        html = """
                     <table width="600">
                        <tr width="600" color="#000000">
                            <td width="80%">
                               Perfumeria La que vende perfumes <br>
                               LABOULAYE, CORDOBA, ARGENTINA <br>
                               TEL: 0351-111111  <br>
                               MAIL: [email protected]  <br>
                            </td>
                            <td width="20%" align="right">
                                <IMG SRC="kde1.png">
                            </td>
                        </tr>

                    </table>
                _______________________________________________________________________________________________________
                    <p>
                        DATOS DEL CLIENTE:
                    </p>
                    <br>
                    <table>

                        <tr>
                            <td>
                                NOMBRE:   """ + nombre + """  <br>
                                APELLIDO: """ + apellido + """ <br>

                            </td>
                            <td>
                            </td>
                        </tr>
                    </table>

                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <p>
                        DETALLES DE LA COMPRA:
                    </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="10%"  align="center" valign="middle">
                            <b>
                            CANT
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                                PRODUCTO
                            </b>
                        </td>
                        <td width="50%"  align="center" valign="middle">
                            <b>
                            DESCRIPCION
                            </b>
                        </td>
                        <td width="10%"  align="center" valign="middle">
                            <b>
                            PREC <br>UNIT
                            </b>
                        </td>
                        <td width="10%"  align="center" valign="middle">
                            <b>
                            PREC <br>TOT
                            </b>
                        </td>
                      </tr>
                  </table>

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

                  <table  height="350" width="600" style="border-color: gray; border-width: .4px; border-collapse: collapse;">
                      """ + listTransaccionTable + """
                  </table>
                    <br>
                    <br>
                    <table width="600" border="0.5" height="0" style="border-color: black; border-width: 0.5px; border-spacing: 0;">
                        <tr >
                            <td width="90%" align="right">
                                <br>
                                TOTAL..................................................................................................................
                                <br>
                            </td>
                            <td width="10%" align="center">
                              <br> $ """ + total + """<br>
                            </td>
                        </tr>
                    </table>

                    <br>
                    <br>
                    <br>
                    <p width="600" align="center" style=" font-size: 10; " >
                    Por cualquier consulta, sobre este recibo, dirigirse al local que se encuentra ubicado en la calle
                    independencia 450. <br> O Comunicarse a los telefonos 03382-123123123 / 4231231
                    </p>
                    <br>
                    <br>
                    <br>
                    <br>
                    <br>
                    _______________________________________________________________________________________________________
                    <br>
                    <table width="600">
                        <tr>
                            <td align="right" width="80%">
                            FECHA/HORA : """ + fecha + """
                            </td>
                            <td align="right">
                            N° : """ + str(idRecibo) + """
                            </td>
                        </tr>
                    </table>
                    _______________________________________________________________________________________________________
                """

        doc = QTextDocument()
        doc.setHtml(html)
        #doc.setDefaultStyleSheet(style)
        printer = QPrinter()
        printer.setOutputFileName(nombrePdf)

        printer.setOutputFormat(QPrinter.PdfFormat)
        doc.print(printer)
        printer.newPage()
        url = QUrl
        url = QUrl(nombrePdf)
        QDesktopServices.openUrl(url)
コード例 #38
0
    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)
コード例 #39
0
    def createList(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.listFinal:
            listTable += """
                                        <tr height="80">
                                            <td width="40%" align="center" >
                                            <br>""" + str(lista[0])  + """<br>
                                            </td>
                                            <td width="40%" >
                                                <br> &nbsp;&nbsp;""" + str(lista[1])  + """<br>
                                            </td>
                                            <td width="20%" >
                                               <br>&nbsp;&nbsp; """ + str(lista[2])  + """<br>
                                            </td>
                                        </tr>
                                   """


        subtitle = "Listado de clientes con deudas : "
        if self.type == 'PROV':
            subtitle = "Listado de deudas a proveedores : "


        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>
                        """+ subtitle + """
                    </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="40%"  align="center" valign="middle">
                            <b>
                            APELLIDO
                            </b>
                        </td>
                        <td width="40%"  align="center" valign="middle">
                            <b>
                                NOMBRE
                            </b>
                        </td>
                        <td width="20%"  align="center" valign="middle">
                            <b>
                            DEUDA
                            </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)
コード例 #40
0
ファイル: delegates.py プロジェクト: qunxyz/calibre
 def __init__(self, parent):
     QStyledItemDelegate.__init__(self, parent)
     self.document = QTextDocument()