Exemplo n.º 1
0
    def textStyle(self, styleIndex):
        cursor = self.textEdit.textCursor()
        if styleIndex:
            styleDict = {
                1: QTextListFormat.ListDisc,
                2: QTextListFormat.ListCircle,
                3: QTextListFormat.ListSquare,
                4: QTextListFormat.ListDecimal,
                5: QTextListFormat.ListLowerAlpha,
                6: QTextListFormat.ListUpperAlpha,
                7: QTextListFormat.ListLowerRoman,
                8: QTextListFormat.ListUpperRoman,
            }

            style = styleDict.get(styleIndex, QTextListFormat.ListDisc)
            cursor.beginEditBlock()
            blockFmt = cursor.blockFormat()
            listFmt = QTextListFormat()

            if cursor.currentList():
                listFmt = cursor.currentList().format()
            else:
                listFmt.setIndent(blockFmt.indent() + 1)
                blockFmt.setIndent(0)
                cursor.setBlockFormat(blockFmt)

            listFmt.setStyle(style)
            cursor.createList(listFmt)
            cursor.endEditBlock()
        else:
            bfmt = QTextBlockFormat()
            bfmt.setObjectIndex(-1)
            cursor.mergeBlockFormat(bfmt)
Exemplo n.º 2
0
    def textStyle(self, styleIndex):
        cursor = self.textEdit.textCursor()
        if styleIndex:
            styleDict = {
                1: QTextListFormat.ListDisc,
                2: QTextListFormat.ListCircle,
                3: QTextListFormat.ListSquare,
                4: QTextListFormat.ListDecimal,
                5: QTextListFormat.ListLowerAlpha,
                6: QTextListFormat.ListUpperAlpha,
                7: QTextListFormat.ListLowerRoman,
                8: QTextListFormat.ListUpperRoman,
            }

            style = styleDict.get(styleIndex, QTextListFormat.ListDisc)
            cursor.beginEditBlock()
            blockFmt = cursor.blockFormat()
            listFmt = QTextListFormat()

            if cursor.currentList():
                listFmt = cursor.currentList().format()
            else:
                listFmt.setIndent(blockFmt.indent() + 1)
                blockFmt.setIndent(0)
                cursor.setBlockFormat(blockFmt)

            listFmt.setStyle(style)
            cursor.createList(listFmt)
            cursor.endEditBlock()
        else:
            bfmt = QTextBlockFormat()
            bfmt.setObjectIndex(-1)
            cursor.mergeBlockFormat(bfmt)
Exemplo n.º 3
0
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
Exemplo n.º 4
0
 def clear_highlight(self) -> None:
     fmt = QTextBlockFormat()
     fmt.setBackground(QColor('white'))
     block = self.editor.document().firstBlock()
     while block.isValid():
         cursor = QTextCursor(block)
         cursor.setBlockFormat(fmt)
         block = block.next()
Exemplo n.º 5
0
 def highlightBlockBefore(self, text):
     """Highlighting to do before anything else.
     
     When subclassing basicHighlighter, you must call highlightBlockBefore
     before you do any custom highlighting.
     """
     bf = QTextBlockFormat(self._defaultBlockFormat)
     bf.setAlignment(QTextCursor(self.currentBlock()).blockFormat().alignment())
     QTextCursor(self.currentBlock()).setBlockFormat(bf)
Exemplo n.º 6
0
 def highlightBlockBefore(self, text):
     """Highlighting to do before anything else.
     
     When subclassing basicHighlighter, you must call highlightBlockBefore
     before you do any custom highlighting.
     """
     bf = QTextBlockFormat(self._defaultBlockFormat)
     bf.setAlignment(QTextCursor(self.currentBlock()).blockFormat().alignment())
     QTextCursor(self.currentBlock()).setBlockFormat(bf)
Exemplo n.º 7
0
def getThemeBlockFormat(themeDatas):
    bf = QTextBlockFormat()
    bf.setLineHeight(themeDatas["Spacings/LineSpacing"], QTextBlockFormat.ProportionalHeight)
    bf.setTextIndent(themeDatas["Spacings/TabWidth"] * 1 if themeDatas["Spacings/IndendFirstLine"] else 0)
    bf.setTopMargin(themeDatas["Spacings/ParagraphAbove"])
    bf.setBottomMargin(themeDatas["Spacings/ParagraphBelow"])
    return bf
Exemplo n.º 8
0
 def AddLog3(self, iLevel, sMsg):
     """设置背景色"""
     self.m_LogTextEdit.appendPlainText(sMsg)
     myDoc = self.m_LogTextEdit.document()
     fmt = QTextBlockFormat()
     fmt.setBackground(LEVEL_COLOR[iLevel])
     for iNum in range(self.m_LineID, myDoc.lineCount()):
         oTextBlock = myDoc.findBlockByNumber(iNum)
         oCursor = QTextCursor(oTextBlock)
         oCursor.mergeBlockFormat(fmt)
     self.m_LineID = myDoc.lineCount()
Exemplo n.º 9
0
 def set_text_alignment(self):
     ''' Apply the required text alignment within the text box '''
     alignment = self.parentItem().text_alignment
     self.setTextWidth(self.boundingRect().width())
     fmt = QTextBlockFormat()
     fmt.setAlignment(alignment)
     cursor = self.textCursor()
     cursor.select(QTextCursor.Document)
     cursor.mergeBlockFormat(fmt)
     cursor.clearSelection()
     self.setTextCursor(cursor)
Exemplo n.º 10
0
    def reshape(self):
        ''' Update the shape of the edge (redefined function) '''
        path = QPainterPath()
        # If there is a starting point, draw a line to the first curve point
        if self.start_point:
            path.moveTo(self.source_connection.center)
            path.lineTo(self.bezier[0])
        else:
            path.moveTo(self.source_connection.center)
        # Loop over the curve points:
        for group in self.bezier[1:]:
            path.cubicTo(*[point.center for point in group])

        # If there is an ending point, draw a line to it
        if self.end_point:
            path.lineTo(self.end_connection.center)

        end_point = path.currentPosition()
        arrowhead = self.angle_arrow(path)
        path.lineTo(arrowhead[0])
        path.moveTo(end_point)
        path.lineTo(arrowhead[1])
        path.moveTo(end_point)
        try:
            # Add the transition label, if any (none for the START edge)
            font = QFont('arial', pointSize=8)
            metrics = QFontMetrics(font)
            label = self.edge.get('label', '')
            lines = label.split('\n')
            width = metrics.width(max(lines)) # longest line
            height = metrics.height() * len(lines)
            # lp is the position of the center of the text
            pos = self.mapFromScene(*self.edge['lp'])
            if not self.text_label:
                self.text_label = QGraphicsTextItem(
                                 self.edge.get('label', ''), parent=self)
            self.text_label.setX(pos.x() - width / 2)
            self.text_label.setY(pos.y() - height / 2)
            self.text_label.setFont(font)
            # Make horizontal center alignment, as dot does
            self.text_label.setTextWidth(self.text_label.boundingRect().width())
            fmt = QTextBlockFormat()
            fmt.setAlignment(Qt.AlignHCenter)
            cursor = self.text_label.textCursor()
            cursor.select(QTextCursor.Document)
            cursor.mergeBlockFormat(fmt)
            cursor.clearSelection()
            self.text_label.setTextCursor(cursor)
            self.text_label.show()
        except KeyError:
            # no label
            pass
        self.setPath(path)
Exemplo n.º 11
0
    def spacify(self):

        lineHeightStyle = QTextBlockFormat()
        lineHeightStyle.setLineHeight(150, QTextBlockFormat.ProportionalHeight)

        currentBlock = self.document().begin()

        while currentBlock.isValid():

            cursor = QTextCursor(currentBlock)
            cursor.setBlockFormat(lineHeightStyle)

            currentBlock = currentBlock.next()
Exemplo n.º 12
0
 def insertImage(self, qimage, image_name):
     self.moveCursor(QTextCursor.End)
     resource_path = os.path.join(self.resource_folder, image_name) + '.png'
     self.document().addResource(QTextDocument.ImageResource,
                                 QUrl(resource_path), QVariant(qimage))
     image_format = QTextImageFormat()
     image_format.setName(resource_path)
     cursor = self.textCursor()
     block_format = QTextBlockFormat()
     block_format.setAlignment(Qt.AlignCenter)
     cursor.insertBlock(block_format)
     cursor.insertImage(image_format)
     cursor.insertBlock(block_format)
     self.image_resources[resource_path] = qimage
Exemplo n.º 13
0
 def malujLinie(self):
     format = QTextBlockFormat()
     format.setBackground(Qt.white)
     self.setLineFormat(self.aktualna_linia, format)
     self.aktualna_linia = self.player.licznik
     format = QTextBlockFormat()
     format.setBackground(Qt.cyan)
     self.setLineFormat(self.aktualna_linia, format)
Exemplo n.º 14
0
 def show(self):
     """
     No need since we print it as soon as we add a row
     """
     if self.tab_initialized:
         self.text_edit.moveCursor(QTextCursor.End)
         self.text_edit.setTextColor(mapColor('k'))
         cursor = self.text_edit.textCursor()
         block_format = QTextBlockFormat()
         block_format.setAlignment(mapAlignment(Align.Center))
         cursor.insertBlock(block_format)
         cursor.insertHtml(self.html_table_widget.show())
         cursor.insertBlock(block_format)
         self.text_edit.resetFontSize()
     else:
         self.table_widget.show()
Exemplo n.º 15
0
    def grayOutOldContent(self):
        insert = True
        textCursor = self.textCursor()
        if not textCursor.atEnd():
            textCursor.movePosition(QTextCursor.End)
        if textCursor.atStart():
            insert = False
        endFormat = textCursor.charFormat()

        textCursor.select(QTextCursor.Document)

        fmt = endFormat.__class__()
        bgColor = self.palette().base().color()
        fgColor = self.palette().text().color()
        bgFactor = .5
        fgFactor = 1 - bgFactor
        fmt.setForeground(
            QColor(
                bgFactor * bgColor.red() + fgFactor * fgColor.red(),
                bgFactor * bgColor.green() + fgFactor * fgColor.green(),
                bgFactor * bgColor.blue() + fgFactor * fgColor.blue(),
            ))
        textCursor.mergeCharFormat(fmt)

        textCursor.movePosition(QTextCursor.End)
        textCursor.setCharFormat(endFormat)
        if insert:
            textCursor.insertBlock(QTextBlockFormat())
        self.setTextCursor(textCursor)
Exemplo n.º 16
0
    def __init__(self, editor):
        QSyntaxHighlighter.__init__(self, editor.document())

        self.editor = editor
        self._misspelledColor = Qt.red
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
Exemplo n.º 17
0
    def __init__(self, editor):
        QSyntaxHighlighter.__init__(self, editor.document())

        self.editor = editor
        self._misspelledColor = Qt.red
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
        self.defaultTextColor = QColor(S.text)
        self.backgroundColor = QColor(S.base)
        self.markupColor = QColor(S.textLight)
        self.linkColor = QColor(S.link)
        self.spellingErrorColor = QColor(Qt.red)
Exemplo n.º 18
0
 def readfile(self):
     self.infodic.clear()
     filename = QFileDialog.getOpenFileName(self, 'Open File Dialog', 'C:',
                                            "Txt files(*.txt)")
     ch = []
     i = 0
     f = open(filename[0], 'r')
     #重置输出框
     self.TB1.setText('Grading\n d\tper')
     #设置TextEdit行高
     text_format = QTextBlockFormat()
     text_format.setBottomMargin(0)
     text_format.setLineHeight(15, QTextBlockFormat.FixedHeight)
     text_cursor = self.TB1.textCursor()
     text_cursor.setBlockFormat(text_format)
     self.TB1.setTextCursor(text_cursor)
     try:
         while True:
             lines = f.readline()
             if not lines.strip():
                 break
             d_tmp, p_tmp = [float(i) for i in lines.split()]
             self.TB1.append(str(d_tmp) + '\t' + str(p_tmp) + '\n')
             self.infodic[d_tmp] = p_tmp
         f.close()
     except:
         QMessageBox.warning(self, 'Warning', 'Invalid Input Format',
                             QMessageBox.Yes)
         return
Exemplo n.º 19
0
    def loadFontSettings(self):
        if self._fromTheme or \
                not self._index or \
                    type(self._index.model()) != outlineModel or \
                    self._column != Outline.text.value:
            return

        opt = settings.textEditor
        f = QFont()
        f.fromString(opt["font"])
        # self.setFont(f)
        self.setStyleSheet("""QTextEdit{{
            background: {bg};
            color: {foreground};
            font-family: {ff};
            font-size: {fs};
            }}
            """.format(bg=opt["background"],
                       foreground=opt["fontColor"],
                       ff=f.family(),
                       fs="{}pt".format(str(f.pointSize()))))

        cf = QTextCharFormat()
        # cf.setFont(f)
        # cf.setForeground(QColor(opt["fontColor"]))

        bf = QTextBlockFormat()
        bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight)
        bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0)
        bf.setTopMargin(opt["spacingAbove"])
        bf.setBottomMargin(opt["spacingBelow"])

        self._defaultCharFormat = cf
        self._defaultBlockFormat = bf

        if self.highlighter:
            self.highlighter.setMisspelledColor(QColor(opt["misspelled"]))
            self.highlighter.setDefaultCharFormat(self._defaultCharFormat)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 20
0
    def highlightBlockBefore(self, text):
        """Highlighting to do before anything else.

        When subclassing BasicHighlighter, you must call highlightBlockBefore
        before you do any custom highlighting. Or implement doHighlightBlock.
        """

        #LOGGER.debug("undoSteps before: %s", self.currentBlock().document().availableUndoSteps())
        c = QTextCursor(self.currentBlock())
        #c.joinPreviousEditBlock()
        bf = QTextBlockFormat(self._defaultBlockFormat)
        if bf != c.blockFormat():
            c.setBlockFormat(bf)
Exemplo n.º 21
0
    def reset(self):
        self.b_pause.setEnabled(False)
        self.b_start.setEnabled(True)
        self.combo_plansze.setEnabled(True)
        # self.konsola.clear()
        self.textBox.setEnabled(True)

        for j in range(0, len(self.textBox.toPlainText().splitlines())):
            format = QTextBlockFormat()
            format.setBackground(Qt.white)
            self.setLineFormat(j, format)

    # DZIALAJACY RESET
        for t in self.threads_list:
            if t.is_alive():
                t.raiseExc(SystemExit)
                time.sleep(0.1)
                pass
        self.threads_list = []
        self.player_thread = None
        self.timer.stop()
        self.timer_action.stop()
        self.map_init(str(self.combo_plansze.currentText()))
Exemplo n.º 22
0
    def loadFontSettings(self):
        if self._fromTheme or \
                not self._index or \
                    type(self._index.model()) != outlineModel or \
                    self._column != Outline.text.value:
            return

        opt = settings.textEditor
        f = QFont()
        f.fromString(opt["font"])
        # self.setFont(f)
        self.setStyleSheet("""QTextEdit{{
            background: {bg};
            color: {foreground};
            font-family: {ff};
            font-size: {fs};
            }}
            """.format(
                bg=opt["background"],
                foreground=opt["fontColor"],
                ff=f.family(),
                fs="{}pt".format(str(f.pointSize()))))

        cf = QTextCharFormat()
        # cf.setFont(f)
        # cf.setForeground(QColor(opt["fontColor"]))

        bf = QTextBlockFormat()
        bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight)
        bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0)
        bf.setTopMargin(opt["spacingAbove"])
        bf.setBottomMargin(opt["spacingBelow"])

        self._defaultCharFormat = cf
        self._defaultBlockFormat = bf

        if self.highlighter:
            self.highlighter.setMisspelledColor(QColor(opt["misspelled"]))
            self.highlighter.setDefaultCharFormat(self._defaultCharFormat)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 23
0
    def __init__(self, editor):
        QSyntaxHighlighter.__init__(self, editor.document())

        self.editor = editor
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
        self.defaultTextColor = QColor(S.text)
        self.backgroundColor = QColor(S.base)
        self.markupColor = QColor(S.textLight)
        self.linkColor = QColor(S.link)
        self.spellingErrorColor = QColor(Qt.red)

        # Matches during checking can be separated by their type (all of them listed here):
        # https://languagetool.org/development/api/org/languagetool/rules/ITSIssueType.html
        #
        # These are the colors for actual spell-, grammar- and style-checking:
        self._errorColors = {
            'addition' : QColor(255, 215, 0),               # gold
            'characters' : QColor(135, 206, 235),           # sky blue
            'duplication' : QColor(0, 255, 255),            # cyan / aqua
            'formatting' : QColor(0, 128, 128),             # teal
            'grammar' : QColor(0, 0, 255),                  # blue
            'inconsistency' : QColor(128, 128, 0),          # olive
            'inconsistententities' : QColor(46, 139, 87),   # sea green
            'internationalization' : QColor(255, 165, 0),   # orange
            'legal' : QColor(255, 69, 0),                   # orange red
            'length' : QColor(47, 79, 79),                  # dark slate gray
            'localespecificcontent' : QColor(188, 143, 143),# rosy brown
            'localeviolation' : QColor(128, 0, 0),          # maroon
            'markup' : QColor(128, 0, 128),                 # purple
            'misspelling' : QColor(255, 0, 0),              # red
            'mistranslation' : QColor(255, 0, 255),         # magenta / fuchsia
            'nonconformance' : QColor(255, 218, 185),       # peach puff
            'numbers' : QColor(65, 105, 225),               # royal blue
            'omission' : QColor(255, 20, 147),              # deep pink
            'other' : QColor(138, 43, 226),                 # blue violet
            'patternproblem' : QColor(0, 128, 0),           # green
            'register' : QColor(112,128,144),               # slate gray
            'style' : QColor(0, 255, 0),                    # lime
            'terminology' : QColor(0, 0, 128),              # navy
            'typographical' : QColor(255, 255, 0),          # yellow
            'uncategorized' : QColor(128, 128, 128),        # gray
            'untranslated' : QColor(210, 105, 30),          # chocolate
            'whitespace' : QColor(192, 192, 192)            # silver
        }
Exemplo n.º 24
0
    def creategridbox(self):
        self.gridbox = QGroupBox()
        grid = QGridLayout()
        '''
        self.fig = Figure(figsize=(5, 10), dpi=100)
        self.canvas=FigureCanvas(self.fig)
        self.toolbar=MyCostumToolbar(self.canvas,self)
        btn=QPushButton('Grading Curve')
        btn.clicked.connect(self.plot)
        '''

        self.btr = QPushButton('Read File')
        self.btr.clicked.connect(self.readfile)
        self.bth = QPushButton('Help')
        self.bth.clicked.connect(self.helpfile)

        self.TB1 = QTextEdit('Grading')
        self.TB1.setFixedSize(150, 250)
        #设置TextEdit行高
        text_format = QTextBlockFormat()
        text_format.setBottomMargin(0)
        text_format.setLineHeight(15, QTextBlockFormat.FixedHeight)
        text_cursor = self.TB1.textCursor()
        text_cursor.setBlockFormat(text_format)
        self.TB1.setTextCursor(text_cursor)

        Lbn = QLabel('Particle Number')  #不少于100个
        self.LEn = QLineEdit('200')
        Lbr = QLabel('Specimen Slenderness')
        self.LEr = QLineEdit('2')
        Lbe = QLabel('Estimated Void Ratio')
        self.LEe = QLineEdit('0.5')

        self.LEn.setFixedWidth(100)
        self.LEr.setFixedWidth(100)
        self.LEe.setFixedWidth(100)

        #set the layout
        grid.addWidget(self.btr, 0, 0, 1, 1)
        grid.addWidget(self.bth, 0, 6, 1, 1)
        grid.addWidget(self.TB1, 1, 0, 15, 4)

        grid.addWidget(Lbn, 1, 5, 1, 1)
        grid.addWidget(self.LEn, 1, 6, 1, 1)
        grid.addWidget(Lbr, 2, 5, 1, 1)
        grid.addWidget(self.LEr, 2, 6, 1, 1)
        grid.addWidget(Lbe, 3, 5, 1, 1)
        grid.addWidget(self.LEe, 3, 6, 1, 1)
        grid.setHorizontalSpacing(15)
        self.gridbox.setLayout(grid)

        self.gridbox.setWindowTitle('test')
    def gray_out_old_text(self):
        """Puts the old text in gray"""

        cursor = self.textCursor()
        end_format = cursor.charFormat()
        cursor.select(QTextCursor.Document)
        format_ = QTextCharFormat()
        backcolor = self.palette().base().color()
        forecolor = self.palette().text().color()
        backfactor = .5
        forefactor = 1 - backfactor
        red = backfactor * backcolor.red() + forefactor * forecolor.red()
        green = backfactor * backcolor.green() + forefactor * forecolor.green()
        blue = backfactor * backcolor.blue() + forefactor * forecolor.blue()
        format_.setForeground(QColor(red, green, blue))
        cursor.mergeCharFormat(format_)
        cursor.movePosition(QTextCursor.End)
        cursor.setCharFormat(end_format)
        cursor.insertBlock(QTextBlockFormat())
Exemplo n.º 26
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_GenresOptionsPage()
        self.ui.setupUi(self)

        self.ui.genres_filter.setToolTip(_(TOOLTIP_GENRES_FILTER))
        self.ui.genres_filter.textChanged.connect(self.update_test_genres_filter)

        self.ui.test_genres_filter.setToolTip(_(TOOLTIP_TEST_GENRES_FILTER))
        self.ui.test_genres_filter.textChanged.connect(self.update_test_genres_filter)

        # FIXME: colors aren't great from accessibility POV
        self.fmt_keep = QTextBlockFormat()
        self.fmt_keep.setBackground(Qt.green)

        self.fmt_skip = QTextBlockFormat()
        self.fmt_skip.setBackground(Qt.red)

        self.fmt_clear = QTextBlockFormat()
        self.fmt_clear.clearBackground()
Exemplo n.º 27
0
    def formatBlock(self, block, state):
        """Apply transformation to given block."""
        blockFormat = QTextBlockFormat()

        if state == State.BLOCKQUOTE_LINE:
            # Number of tabs
            n = block.text().indexOf(QRegExp(r'[^\t]'), 0)
            blockFormat.setIndent(0)
            blockFormat.setTextIndent(-self.tabStopWidth * n)
            blockFormat.setLeftMargin(self.tabStopWidth * n)
            # blockFormat.setRightMargin(self.editor.contentsRect().width()
            # - self.editor.lineNumberAreaWidth()
            # - fm.width("X") * self.editor.LimitLine
            # + self.editor.tabStopWidth())
            blockFormat.setAlignment(Qt.AlignJustify)
            if self.name == "Default":
                blockFormat.setTopMargin(5)
                blockFormat.setBottomMargin(5)
        elif state == State.HEADER_LINE:
            blockFormat.setBackground(QColor("#EEEEEE"))
        elif state in State.LIST:
            data = blockUserData.getUserData(block)
            if str(data.listSymbol()) in "+-":
                blockFormat.setBackground(QColor("#EEFFEE"))
            else:
                blockFormat.setBackground(QColor("#EEEEFA"))
            n = blockUserData.getUserData(block).leadingSpaces() + 1

            f = QFontMetrics(QFont(self.defaultFontFamily,
                                   self._defaultCharFormat.font().pointSize()))
            fm = f.width(" " * n +
                         blockUserData.getUserData(block).listSymbol())
            blockFormat.setTextIndent(-fm)
            blockFormat.setLeftMargin(fm)
            if blockUserData.getUserState(block) == State.LIST_BEGINS and \
                            self.name == "Default":
                blockFormat.setTopMargin(5)
        return blockFormat
Exemplo n.º 28
0
    def CreatePDF(self, out, timestamp, data, frame, rows, columns, fileName,
                  VManager):
        ''' Create PDF QgsTask '''
        QCoreApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        font_normal = QFont("Helvetica", 10, QFont.Normal)
        font_bold = QFont("Helvetica", 12, QFont.Bold)

        printer = QPrinter(QPrinter.HighResolution)
        printer.setOrientation(QPrinter.Portrait)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setFullPage(True)
        printer.setPaperSize(QPrinter.A4)
        printer.setOutputFileName(out)
        printer.setPageMargins(15, 15, 15, 15, QPrinter.Point)
        printer.setColorMode(QPrinter.Color)

        document = QTextDocument()
        document.setDefaultFont(font_normal)

        cursor = QTextCursor(document)
        cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)
        cursor.insertHtml("""
            <p style='text-align: center;'>
            <img style='display: block; margin-left: auto; margin-right: auto;' 
            src=\':/imgFMV/images/header_logo.png\' width='200' height='25' />
            </p>
            <p style='text-align: center;'>
            <strong>Video :&nbsp;</strong>%s<strong>
            </p>
            <p style='text-align: center;'>
            <strong>TimeStamp :&nbsp;</strong>%s</p><br><br>
            """ % (fileName, timestamp))

        tableFormat = QTextTableFormat()
        tableFormat.setHeaderRowCount(1)
        tableFormat.setBorderBrush(QBrush(Qt.black))
        tableFormat.setAlignment(Qt.AlignHCenter)
        tableFormat.setCellPadding(2)
        tableFormat.setCellSpacing(2)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignCenter)
        cursor.insertBlock(centerFormat)

        textTable = cursor.insertTable(rows + 1, columns, tableFormat)

        tableHeaderFormat = QTextCharFormat()
        tableHeaderFormat.setFont(font_bold)
        tableHeaderFormat.setBackground(QColor("#67b03a"))
        tableHeaderFormat.setForeground(Qt.white)

        alternate_background = QTextCharFormat()
        alternate_background.setBackground(QColor("#DDE9ED"))

        for column in range(columns):
            cell = textTable.cellAt(0, column)
            cell.setFormat(tableHeaderFormat)
            cellCursor = cell.firstCursorPosition()
            cellCursor.insertText(VManager.horizontalHeaderItem(column).text())

        row = 0
        for key in sorted(data.keys()):
            cell0 = textTable.cellAt(row + 1, 0)
            cell1 = textTable.cellAt(row + 1, 1)
            cell2 = textTable.cellAt(row + 1, 2)
            if (row + 1) % 2 == 0:
                cell0.setFormat(alternate_background)
                cell1.setFormat(alternate_background)
                cell2.setFormat(alternate_background)
            cellCursor0 = cell0.firstCursorPosition()
            cellCursor0.insertText(str(key))
            cellCursor1 = cell1.firstCursorPosition()
            cellCursor1.insertText(str(data[key][0]))
            cellCursor2 = cell2.firstCursorPosition()
            cellCursor2.insertText(str(data[key][1]))
            row += 1

        cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)

        cursor.insertHtml("""
        <br><p style='text-align: center;'><strong>Current Frame</strong></p><br>
        """)

        centerFormat = QTextBlockFormat()
        centerFormat.setAlignment(Qt.AlignHCenter)
        cursor.insertBlock(centerFormat)
        cursor.insertImage(frame.scaledToWidth(500))
        QCoreApplication.processEvents()
        document.print_(printer)
        QCoreApplication.processEvents()
Exemplo n.º 29
0
    def __init__(self,
                 parent=None,
                 index=None,
                 html=None,
                 spellcheck=None,
                 highlighting=False,
                 dict="",
                 autoResize=False):
        QTextEdit.__init__(self, parent)
        self._column = Outline.text
        self._index = None
        self._indexes = None
        self._model = None
        self._placeholderText = self.placeholderText()
        self._updating = QMutex()
        self._item = None
        self._highlighting = highlighting
        self._textFormat = "text"
        self.setAcceptRichText(False)
        # When setting up a theme, this becomes true.
        self._fromTheme = False
        self._themeData = None
        self._highlighterClass = BasicHighlighter

        if spellcheck == None:
            spellcheck = settings.spellcheck

        self.spellcheck = spellcheck
        self.currentDict = dict if dict else settings.dict
        self._defaultFontSize = qApp.font().pointSize()
        self.highlighter = None
        self.setAutoResize(autoResize)
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
        self.highlightWord = ""
        self.highligtCS = False
        self._dict = None
        self._tooltip = {'depth': 0, 'active': 0}

        # self.document().contentsChanged.connect(self.submit, F.AUC)

        # Submit text changed only after 500ms without modifications
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(500)
        self.updateTimer.setSingleShot(True)
        self.updateTimer.timeout.connect(self.submit)
        # self.updateTimer.timeout.connect(lambda: LOGGER.debug("Timeout."))

        self.updateTimer.stop()
        self.document().contentsChanged.connect(self.updateTimer.start, F.AUC)
        # self.document().contentsChanged.connect(lambda: LOGGER.debug("Document changed."))

        # self.document().contentsChanged.connect(lambda: LOGGER.debug("Contents changed: %s", self.objectName()))

        self.setEnabled(False)

        if index:
            self.setCurrentModelIndex(index)

        elif html:
            self.document().setHtml(html)
            self.setReadOnly(True)

        # Spellchecking
        if self.spellcheck:
            self._dict = Spellchecker.getDictionary(self.currentDict)

        if not self._dict:
            self.spellcheck = False

        if self._highlighting and not self.highlighter:
            self.highlighter = self._highlighterClass(self)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 30
0
    def loadFontSettings(self):
        if self._fromTheme or \
                not self._index or \
                    type(self._index.model()) != outlineModel or \
                    self._column != Outline.text:
            return

        opt = settings.textEditor
        f = QFont()
        f.fromString(opt["font"])
        background = (opt["background"] if not opt["backgroundTransparent"]
                      else "transparent")
        foreground = opt["fontColor"] # if not opt["backgroundTransparent"]
        #                               else S.text
        # self.setFont(f)
        self.setStyleSheet("""QTextEdit{{
            background: {bg};
            color: {foreground};
            font-family: {ff};
            font-size: {fs};
            margin: {mTB}px {mLR}px;
            {maxWidth}
            }}
            """.format(
                bg=background,
                foreground=foreground,
                ff=f.family(),
                fs="{}pt".format(str(f.pointSize())),
                mTB = opt["marginsTB"],
                mLR = opt["marginsLR"],
                maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "",
                )
            )
        self._defaultFontSize = f.pointSize()

        # We set the parent background to the editor's background in case
        # there are margins. We check that the parent class is a QWidget because
        # if textEditView is used in fullScreenEditor, then we don't want to
        # set the background.
        if self.parent().__class__ == QWidget:
            self.parent().setStyleSheet("""
                QWidget#{name}{{
                    background: {bg};
                }}""".format(
                    # We style by name, otherwise all inheriting widgets get the same
                    # colored background, for example context menu.
                    name=self.parent().objectName(),
                    bg=background,
                ))

        cf = QTextCharFormat()
        # cf.setFont(f)
        # cf.setForeground(QColor(opt["fontColor"]))

        self.setCursorWidth(opt["cursorWidth"])

        bf = QTextBlockFormat()
        bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight)
        bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0)
        bf.setTopMargin(opt["spacingAbove"])
        bf.setBottomMargin(opt["spacingBelow"])
        bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else
                        Qt.AlignCenter if opt["textAlignment"] == 1 else
                        Qt.AlignRight if opt["textAlignment"] == 2 else
                        Qt.AlignJustify)

        self._defaultCharFormat = cf
        self._defaultBlockFormat = bf

        if self.highlighter:
            self.highlighter.updateColorScheme()
            self.highlighter.setMisspelledColor(QColor(opt["misspelled"]))
            self.highlighter.setDefaultCharFormat(self._defaultCharFormat)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 31
0
class GenresOptionsPage(OptionsPage):

    NAME = "genres"
    TITLE = N_("Genres")
    PARENT = "metadata"
    SORT_ORDER = 20
    ACTIVE = True
    HELP_URL = '/config/options_genres.html'

    options = [
        BoolOption("setting", "use_genres", False),
        IntOption("setting", "max_genres", 5),
        IntOption("setting", "min_genre_usage", 90),
        TextOption("setting", "genres_filter",
                   "-seen live\n-favorites\n-fixme\n-owned"),
        TextOption("setting", "join_genres", ""),
        BoolOption("setting", "only_my_genres", False),
        BoolOption("setting", "artists_genres", False),
        BoolOption("setting", "folksonomy_tags", False),
    ]

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_GenresOptionsPage()
        self.ui.setupUi(self)

        self.ui.genres_filter.setToolTip(_(TOOLTIP_GENRES_FILTER))
        self.ui.genres_filter.textChanged.connect(
            self.update_test_genres_filter)

        self.ui.test_genres_filter.setToolTip(_(TOOLTIP_TEST_GENRES_FILTER))
        self.ui.test_genres_filter.textChanged.connect(
            self.update_test_genres_filter)

        # FIXME: colors aren't great from accessibility POV
        self.fmt_keep = QTextBlockFormat()
        self.fmt_keep.setBackground(Qt.green)

        self.fmt_skip = QTextBlockFormat()
        self.fmt_skip.setBackground(Qt.red)

        self.fmt_clear = QTextBlockFormat()
        self.fmt_clear.clearBackground()

    def load(self):
        config = get_config()
        self.ui.use_genres.setChecked(config.setting["use_genres"])
        self.ui.max_genres.setValue(config.setting["max_genres"])
        self.ui.min_genre_usage.setValue(config.setting["min_genre_usage"])
        self.ui.join_genres.setEditText(config.setting["join_genres"])
        self.ui.genres_filter.setPlainText(config.setting["genres_filter"])
        self.ui.only_my_genres.setChecked(config.setting["only_my_genres"])
        self.ui.artists_genres.setChecked(config.setting["artists_genres"])
        self.ui.folksonomy_tags.setChecked(config.setting["folksonomy_tags"])

    def save(self):
        config = get_config()
        config.setting["use_genres"] = self.ui.use_genres.isChecked()
        config.setting["max_genres"] = self.ui.max_genres.value()
        config.setting["min_genre_usage"] = self.ui.min_genre_usage.value()
        config.setting["join_genres"] = self.ui.join_genres.currentText()
        config.setting["genres_filter"] = self.ui.genres_filter.toPlainText()
        config.setting["only_my_genres"] = self.ui.only_my_genres.isChecked()
        config.setting["artists_genres"] = self.ui.artists_genres.isChecked()
        config.setting["folksonomy_tags"] = self.ui.folksonomy_tags.isChecked()

    def update_test_genres_filter(self):
        test_text = self.ui.test_genres_filter.toPlainText()

        filters = self.ui.genres_filter.toPlainText()
        tagfilter = TagGenreFilter(filters)

        # FIXME: very simple error reporting, improve
        self.ui.label_test_genres_filter_error.setText("\n".join([
            _("Error line %d: %s") % (lineno + 1, error)
            for lineno, error in tagfilter.errors.items()
        ]))

        def set_line_fmt(lineno, textformat):
            obj = self.ui.test_genres_filter
            if lineno < 0:
                # use current cursor position
                cursor = obj.textCursor()
            else:
                cursor = QTextCursor(obj.document().findBlockByNumber(lineno))
            obj.blockSignals(True)
            cursor.setBlockFormat(textformat)
            obj.blockSignals(False)

        set_line_fmt(-1, self.fmt_clear)
        for lineno, line in enumerate(test_text.splitlines()):
            line = line.strip()
            fmt = self.fmt_clear
            if line:
                if tagfilter.skip(line):
                    fmt = self.fmt_skip
                else:
                    fmt = self.fmt_keep
            set_line_fmt(lineno, fmt)
Exemplo n.º 32
0
    def creategridbox(self):
        self.gridbox = QGroupBox()
        self.bot_tabs = QTabWidget()
        self.input_tab = QWidget()
        self.setting_tab = QWidget()
        self.output_tab = QWidget()
        self.bot_tabs.addTab(self.input_tab, 'Input')
        self.bot_tabs.addTab(self.setting_tab, 'Setting')
        self.bot_tabs.addTab(self.output_tab, 'Output')

        #set the layout for input tab
        grid1 = QGridLayout()
        self.t_ch_box = QCheckBox('Scan Thickness')
        self.t_ch_box.setChecked(False)
        self.t_ch_box.stateChanged.connect(self.if_scan)
        self.m_ch_box = QCheckBox('Metal Material')
        self.m_ch_box.setChecked(True)
        self.e_ch_box = QCheckBox('Draw  ε')
        self.e_ch_box.setChecked(True)
        self.m_ch_box.stateChanged.connect(self.if_metal)

        self.lb_t = QLabel('Thickness  (nm)')
        self.le_t = QLineEdit('10')
        self.le_t.setFixedWidth(100)
        self.le_t.setToolTip('scan and fit thickness if leave it blank')
        self.lb_t_min = QLabel('min Thickness  (nm)')
        self.le_t_min = QLineEdit('')
        self.le_t_min.setFixedWidth(100)
        self.lb_t_tol = QLabel('Thickness Tolerance  (nm)')
        self.le_t_tol = QLineEdit('')
        self.le_t_tol.setFixedWidth(100)
        lb_R = QLabel('Reflectance  (%s)' %
                      chr(248))  #use ASCII to get the icon
        self.le_R = QLineEdit('0 50 60')

        #hide sth
        self.lb_t_min.hide()
        self.le_t_min.hide()
        self.lb_t_tol.hide()
        self.le_t_tol.hide()

        lb_T = QLabel('Transmittance  (%s)' % chr(248))
        self.le_T = QLineEdit('0')
        lb_upload = QLabel('Upload Files')
        hbox = QHBoxLayout()
        btn_load_R = QPushButton('Reflectance')
        btn_load_R.setFixedWidth(120)
        btn_load_R.clicked.connect(self.readfile)
        btn_load_T = QPushButton('Transmittance')
        btn_load_T.setFixedWidth(120)
        btn_load_T.clicked.connect(self.readfile)
        btn_load_nk = QPushButton('nk file')
        btn_load_nk.setFixedWidth(120)
        btn_load_nk.clicked.connect(self.readfile)

        hbox.addWidget(btn_load_R, Qt.AlignLeft)
        hbox.addStretch(1)
        hbox.addWidget(btn_load_T, Qt.AlignHCenter)
        hbox.addStretch(1)
        hbox.addWidget(btn_load_nk, Qt.AlignRight)

        grid1.addWidget(self.t_ch_box, 0, 0, 1, 1)
        grid1.addWidget(self.m_ch_box, 0, 2, 1, 1)
        grid1.addWidget(self.e_ch_box, 0, 4, 1, 1)
        grid1.addWidget(self.lb_t, 1, 0, 1, 1)
        grid1.addWidget(self.le_t, 1, 1, 1, 1)
        grid1.addWidget(self.lb_t_min, 1, 2, 1, 1)
        grid1.addWidget(self.le_t_min, 1, 3, 1, 1)
        grid1.addWidget(self.lb_t_tol, 1, 4, 1, 1)
        grid1.addWidget(self.le_t_tol, 1, 5, 1, 1)

        grid1.addWidget(lb_R, 2, 0, 1, 1)
        grid1.addWidget(self.le_R, 2, 1, 1, 5)

        grid1.addWidget(lb_T, 3, 0, 1, 1)
        grid1.addWidget(self.le_T, 3, 1, 1, 5)

        grid1.addWidget(lb_upload, 4, 0, 1, 1)
        grid1.setRowStretch(3, 20)
        grid1.setColumnMinimumWidth(1, 200)
        grid1.setColumnMinimumWidth(3, 200)
        grid1.setColumnMinimumWidth(5, 100)
        grid1.addLayout(hbox, 5, 0, 1, 6)

        self.input_tab.setLayout(grid1)

        #set the layout for setting tab
        grid3 = QGridLayout()
        lb_tol = QLabel('tolerance')
        self.le_tol = QLineEdit('0.00001')
        self.le_tol.setFixedWidth(100)
        lb_thes_min = QLabel('threshold_min')
        self.le_thes_min = QLineEdit('0.001')
        self.le_thes_min.setFixedWidth(100)
        lb_thes_max = QLabel('threshold_max')
        self.le_thes_max = QLineEdit('0.01')
        self.le_thes_max.setFixedWidth(100)
        lb_lam_min = QLabel('lamda_min (nm)')
        self.le_lam_min = QLineEdit()
        self.le_lam_min.setFixedWidth(100)
        lb_lam_max = QLabel('lamda_max (nm)')
        self.le_lam_max = QLineEdit()
        self.le_lam_max.setFixedWidth(100)
        grid3.addWidget(lb_tol, 2, 0, 1, 1)
        grid3.addWidget(self.le_tol, 2, 1, 1, 1)
        grid3.addWidget(lb_thes_min, 1, 0, 1, 1)
        grid3.addWidget(self.le_thes_min, 1, 1, 1, 1)
        grid3.addWidget(lb_thes_max, 1, 2, 1, 1)
        grid3.addWidget(self.le_thes_max, 1, 3, 1, 1)
        grid3.addWidget(lb_lam_min, 0, 0, 1, 1)
        grid3.addWidget(self.le_lam_min, 0, 1, 1, 1)
        grid3.addWidget(lb_lam_max, 0, 2, 1, 1)
        grid3.addWidget(self.le_lam_max, 0, 3, 1, 1)
        grid3.setColumnMinimumWidth(1, 200)
        grid3.setColumnMinimumWidth(3, 200)
        grid3.setRowMinimumHeight(1, 60)
        grid3.setColumnStretch(4, 1)
        grid3.setRowStretch(2, 1)
        self.setting_tab.setLayout(grid3)

        #set the layout for output tab
        grid2 = QGridLayout()

        self.TB1 = QTextEdit('')

        #set the height of QTextEdit
        text_format = QTextBlockFormat()
        text_format.setBottomMargin(0)
        text_format.setLineHeight(15, QTextBlockFormat.FixedHeight)
        text_cursor = self.TB1.textCursor()
        text_cursor.setBlockFormat(text_format)
        self.TB1.setTextCursor(text_cursor)

        self.TB1.verticalScrollBar().rangeChanged.connect(self.tb_scroll)
        #self.TB1.moveCursor(QTextCursor.End)

        self.bth = QPushButton('Help')
        self.bth.clicked.connect(self.helpfile)
        hbox2 = QHBoxLayout()
        hbox2.addStretch(1)
        #hbox2.addWidget(self.bth)

        grid2.addWidget(self.TB1, 0, 0, 10, 2)
        grid2.addLayout(hbox2, 10, 0, 1, 2)

        grid2.setVerticalSpacing(10)
        grid2.setHorizontalSpacing(15)
        self.output_tab.setLayout(grid2)

        vbox = QVBoxLayout()
        vbox.addWidget(self.bot_tabs)
        self.gridbox.setLayout(vbox)
Exemplo n.º 33
0
    def __init__(self, parent=None, index=None, html=None, spellcheck=True, highlighting=False, dict="",
                 autoResize=False):
        QTextEdit.__init__(self, parent)
        self._column = Outline.text.value
        self._index = None
        self._indexes = None
        self._model = None
        self._placeholderText = self.placeholderText()
        self._updating = False
        self._item = None
        self._highlighting = highlighting
        self._textFormat = "text"
        self.setAcceptRichText(False)
        # When setting up a theme, this becomes true.
        self._fromTheme = False

        self.spellcheck = spellcheck
        self.currentDict = dict if dict else settings.dict
        self.highlighter = None
        self.setAutoResize(autoResize)
        self._defaultBlockFormat = QTextBlockFormat()
        self._defaultCharFormat = QTextCharFormat()
        self.highlightWord = ""
        self.highligtCS = False
        self.defaultFontPointSize = qApp.font().pointSize()
        self._dict = None
        # self.document().contentsChanged.connect(self.submit, F.AUC)

        # Submit text changed only after 500ms without modifications
        self.updateTimer = QTimer()
        self.updateTimer.setInterval(500)
        self.updateTimer.setSingleShot(True)
        self.updateTimer.timeout.connect(self.submit)
        # self.updateTimer.timeout.connect(lambda: print("Timeout"))

        self.updateTimer.stop()
        self.document().contentsChanged.connect(self.updateTimer.start, F.AUC)
        # self.document().contentsChanged.connect(lambda: print("Document changed"))

        # self.document().contentsChanged.connect(lambda: print(self.objectName(), "Contents changed"))

        self.setEnabled(False)

        if index:
            self.setCurrentModelIndex(index)

        elif html:
            self.document().setHtml(html)
            self.setReadOnly(True)

        # Spellchecking
        if enchant and self.spellcheck:
            try:
                self._dict = enchant.Dict(self.currentDict if self.currentDict else self.getDefaultLocale())
            except enchant.errors.DictNotFoundError:
                self.spellcheck = False

        else:
            self.spellcheck = False

        if self._highlighting and not self.highlighter:
            self.highlighter = basicHighlighter(self)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 34
0
    def loadFontSettings(self):
        if self._fromTheme or \
                not self._index or \
                    type(self._index.model()) != outlineModel or \
                    self._column != Outline.text.value:
            return

        opt = settings.textEditor
        f = QFont()
        f.fromString(opt["font"])
        background = opt["background"] if not opt["backgroundTransparent"] else "transparent"
        foreground = opt["fontColor"] if not opt["backgroundTransparent"] else S.text
        # self.setFont(f)
        self.setStyleSheet("""QTextEdit{{
            background: {bg};
            color: {foreground};
            font-family: {ff};
            font-size: {fs};
            margin: {mTB}px {mLR}px;
            {maxWidth}
            }}
            """.format(
                bg=background,
                foreground=foreground,
                ff=f.family(),
                fs="{}pt".format(str(f.pointSize())),
                mTB = opt["marginsTB"],
                mLR = opt["marginsLR"],
                maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "",
                )
            )

        # We set the parent background to the editor's background in case
        # there are margins. We check that the parent class is a QWidget because
        # if textEditView is used in fullScreenEditor, then we don't want to
        # set the background.
        if self.parent().__class__ == QWidget:
            self.parent().setStyleSheet("""
                QWidget#{name}{{
                    background: {bg};
                }}""".format(
                    # We style by name, otherwise all heriting widgets get the same
                    # colored background, for example context menu.
                    name=self.parent().objectName(),
                    bg=background,
                ))

        cf = QTextCharFormat()
        # cf.setFont(f)
        # cf.setForeground(QColor(opt["fontColor"]))

        self.setCursorWidth(opt["cursorWidth"])

        bf = QTextBlockFormat()
        bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight)
        bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0)
        bf.setTopMargin(opt["spacingAbove"])
        bf.setBottomMargin(opt["spacingBelow"])
        bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else
                        Qt.AlignCenter if opt["textAlignment"] == 1 else
                        Qt.AlignRight if opt["textAlignment"] == 2 else
                        Qt.AlignJustify)

        self._defaultCharFormat = cf
        self._defaultBlockFormat = bf

        if self.highlighter:
            self.highlighter.setMisspelledColor(QColor(opt["misspelled"]))
            self.highlighter.setDefaultCharFormat(self._defaultCharFormat)
            self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat)
Exemplo n.º 35
0
    def loadFormats(self):
        self.formats = {}

        stylesCSS = pkg_resources.resource_string(data.__name__, 'styles.css')
        print("styles.css file: {}".format(stylesCSS))
        styleSheet = cssutils.parseString(stylesCSS)

        blockFormats = ['title[level="1"]', 
                        'title[level="2"]', 
                        'title[level="3"]', 
                        'para',
                        'tip',
                        'warning',
                        'blockquote',
                        'programlisting[language="java"]',
                        'programlisting[language="cpp"]',
                        'programlisting[language="xml"]',
                        'programlisting[language="sql"]',
                        'programlisting[language="python"]',
                        'programlisting[language="bash"]',
                        'screen']

        for cssKey in blockFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            # get the selector as a tuple of class and one attribute selector
            # (Can be extended later, but currently sufficient)
            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()

            blockFmt = QTextBlockFormat()
            blockFmt.setProperty(QTextFormat.UserProperty, selector)

            value = self.getIntValue(cssRule, 'margin-top')
            if value:
                blockFmt.setTopMargin(value)
            value = self.getIntValue(cssRule, 'margin-right')
            if value:
                blockFmt.setRightMargin(value)
            value = self.getIntValue(cssRule, 'margin-bottom')
            if value:
                blockFmt.setBottomMargin(value)
            value = self.getIntValue(cssRule, 'margin-left')
            if value:
                blockFmt.setLeftMargin(value)
            value = self.getColorValue(cssRule, 'background-color')
            if value:
                blockFmt.setBackground(value)

            charFmt = QTextCharFormat()
            self.setCharFormatAttributes(cssRule, charFmt)

            fmt = Format(blockFmt, charFmt)
            value = self.getStringValue(cssRule, 'white-space')
            if value and value == 'pre':
                fmt.isPre = True
            self.formats[selector] = fmt

### List formats

        listFormats = ['itemizedlist[level="1"]',
                       'itemizedlist[level="2"]',
                       'itemizedlist[level="3"]', 
                       'itemizedlist[level="4"]',
                       'orderedlist[level="1"]',
                       'orderedlist[level="2"]' ,
                       'orderedlist[level="3"]',
                       'orderedlist[level="4"]'] 
        for cssKey in listFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            indent = 0
            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()
            if selector[1] == 'level':
                indent = int(selector[2])

            listFmt = QTextListFormat()
            listFmt.setProperty(QTextFormat.UserProperty, selector)
            listFmt.setIndent(indent)

            value = self.getStringValue(cssRule, 'list-style-type')
            if value:
                if value == 'disc':
                    listFmt.setStyle(QTextListFormat.ListDisc)
                elif value == 'circle':
                    listFmt.setStyle(QTextListFormat.ListCircle)
                elif value == 'square':
                    listFmt.setStyle(QTextListFormat.ListSquare)
                elif value == 'decimal':
                    listFmt.setStyle(QTextListFormat.ListDecimal)

            self.formats[selector] = Format(None, None, listFmt)

### Inline formats

        # Base format (?????)
        pcharFmt = QTextCharFormat()
        pcharFmt.setFontPointSize(10)
        pcharFmt.setFontFamily("Sans")

        inlineFormats = ['emphasis[role="highlight"]', 
                         'emphasis',
                         'code',
                         'link',
                         'olink']

        for cssKey in inlineFormats:
            cssRule = self.simpleLookup(styleSheet, cssKey)

            m = re.match(r'^(\S*?)(?:\[(.*)="(.*)"])?$', cssKey)
            selector = m.groups()

            charFmt = QTextCharFormat(pcharFmt)
            charFmt.setProperty(QTextFormat.UserProperty, selector)

            # TODO: better approach?
            if cssKey in ['link', 'olink']:
                charFmt.setAnchor(True)
            self.setCharFormatAttributes(cssRule, charFmt)

            self.formats[selector] = Format(None, charFmt)

### special formats
        charFmt = QTextCharFormat()
        cssRule = self.simpleLookup(styleSheet, 'searchMarker')
        self.setCharFormatAttributes(cssRule, charFmt)
        self.formats[('searchMarker', None, None)] = Format(None, charFmt)
Exemplo n.º 36
0
 def getFormat(self, fmtId):
     result = self.formats.get(fmtId)
     if result is None:
         result = Format(QTextBlockFormat(), QTextCharFormat(), QTextListFormat())
     return result
Exemplo n.º 37
0
def getThemeBlockFormat(themeDatas):
    bf = QTextBlockFormat()
    bf.setAlignment(Qt.AlignLeft if themeDatas["Spacings/Alignment"] == 0 else
                    Qt.AlignCenter if themeDatas["Spacings/Alignment"] == 1 else
                    Qt.AlignRight if themeDatas["Spacings/Alignment"] == 2 else
                    Qt.AlignJustify)
    bf.setLineHeight(themeDatas["Spacings/LineSpacing"], QTextBlockFormat.ProportionalHeight)
    bf.setTextIndent(themeDatas["Spacings/TabWidth"] * 1 if themeDatas["Spacings/IndentFirstLine"] else 0)
    bf.setTopMargin(themeDatas["Spacings/ParagraphAbove"])
    bf.setBottomMargin(themeDatas["Spacings/ParagraphBelow"])
    return bf
Exemplo n.º 38
0
    def printViaQCursor(self):
        dialog = QPrintDialog(self.printer, self)
        if not dialog.exec_():
            return
        logo = QPixmap(":/logo.png")
        headFormat = QTextBlockFormat()
        headFormat.setAlignment(Qt.AlignLeft)
        headFormat.setTextIndent(self.printer.pageRect().width() -
                                 logo.width() - 216)
        bodyFormat = QTextBlockFormat()
        bodyFormat.setAlignment(Qt.AlignJustify)
        lastParaBodyFormat = QTextBlockFormat(bodyFormat)
        lastParaBodyFormat.setPageBreakPolicy(
            QTextFormat.PageBreak_AlwaysAfter)
        rightBodyFormat = QTextBlockFormat()
        rightBodyFormat.setAlignment(Qt.AlignRight)
        headCharFormat = QTextCharFormat()
        headCharFormat.setFont(QFont("Helvetica", 10))
        bodyCharFormat = QTextCharFormat()
        bodyCharFormat.setFont(QFont("Times", 11))
        redBodyCharFormat = QTextCharFormat(bodyCharFormat)
        redBodyCharFormat.setForeground(Qt.red)
        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(2)

        document = QTextDocument()
        cursor = QTextCursor(document)
        mainFrame = cursor.currentFrame()
        page = 1
        for statement in self.statements:
            cursor.insertBlock(headFormat, headCharFormat)
            cursor.insertImage(":/logo.png")
            for text in ("Greasy Hands Ltd.",
                         "New Lombard Street", "London", "WC13 4PX",
                         QDate.currentDate().toString(DATE_FORMAT)):
                cursor.insertBlock(headFormat, headCharFormat)
                cursor.insertText(text)
            for line in statement.address.split(", "):
                cursor.insertBlock(bodyFormat, bodyCharFormat)
                cursor.insertText(line)
            cursor.insertBlock(bodyFormat)
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Dear {0},".format(statement.contact))
            cursor.insertBlock(bodyFormat)
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            balance = statement.balance()
            cursor.insertText(
                "The balance of your account is $ {0:,.2f}.".format(
                    float(balance)))
            if balance < 0:
                cursor.insertBlock(bodyFormat, redBodyCharFormat)
                cursor.insertText("Please remit the amount owing "
                                  "immediately.")
            else:
                cursor.insertBlock(bodyFormat, bodyCharFormat)
                cursor.insertText("We are delighted to have done "
                                  "business with you.")
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Transactions:")
            table = cursor.insertTable(len(statement.transactions), 3,
                                       tableFormat)
            row = 0
            for date, amount in statement.transactions:
                cellCursor = table.cellAt(row, 0).firstCursorPosition()
                cellCursor.setBlockFormat(rightBodyFormat)
                cellCursor.insertText(date.toString(DATE_FORMAT),
                                      bodyCharFormat)
                cellCursor = table.cellAt(row, 1).firstCursorPosition()
                if amount > 0:
                    cellCursor.insertText("Credit", bodyCharFormat)
                else:
                    cellCursor.insertText("Debit", bodyCharFormat)
                cellCursor = table.cellAt(row, 2).firstCursorPosition()
                cellCursor.setBlockFormat(rightBodyFormat)
                format = bodyCharFormat
                if amount < 0:
                    format = redBodyCharFormat
                cellCursor.insertText("$ {0:,.2f}".format(float(amount)),
                                      format)
                row += 1
            cursor.setPosition(mainFrame.lastPosition())
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("We hope to continue doing business "
                              "with you,")
            cursor.insertBlock(bodyFormat, bodyCharFormat)
            cursor.insertText("Yours sincerely")
            cursor.insertBlock(bodyFormat)
            if page == len(self.statements):
                cursor.insertBlock(bodyFormat, bodyCharFormat)
            else:
                cursor.insertBlock(lastParaBodyFormat, bodyCharFormat)
            cursor.insertText("K. Longrey, Manager")
            page += 1
        document.print_(self.printer)
Exemplo n.º 39
0
def getThemeBlockFormat(themeDatas):
    bf = QTextBlockFormat()
    bf.setAlignment(Qt.AlignLeft if themeDatas["Spacings/Alignment"] == 0 else
                    Qt.AlignCenter if themeDatas["Spacings/Alignment"] == 1 else
                    Qt.AlignRight if themeDatas["Spacings/Alignment"] == 2 else
                    Qt.AlignJustify)
    bf.setLineHeight(themeDatas["Spacings/LineSpacing"], QTextBlockFormat.ProportionalHeight)
    bf.setTextIndent(themeDatas["Spacings/TabWidth"] * 1 if themeDatas["Spacings/IndentFirstLine"] else 0)
    bf.setTopMargin(themeDatas["Spacings/ParagraphAbove"])
    bf.setBottomMargin(themeDatas["Spacings/ParagraphBelow"])
    return bf