Python PyQt5.QtGui.QTextCharFormat() Examples

The following are 30 code examples for showing how to use PyQt5.QtGui.QTextCharFormat(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module PyQt5.QtGui , or try the search function .

Example 1
Project: dcc   Author: amimo   File: sourcewindow.py    License: Apache License 2.0 6 votes vote down vote up
def _get_format_from_style(self, token, style):
        """ Returns a QTextCharFormat for token by reading a Pygments style.
        """
        result = QtGui.QTextCharFormat()
        for key, value in list(style.style_for_token(token).items()):
            if value:
                if key == 'color':
                    result.setForeground(self._get_brush(value))
                elif key == 'bgcolor':
                    result.setBackground(self._get_brush(value))
                elif key == 'bold':
                    result.setFontWeight(QtGui.QFont.Bold)
                elif key == 'italic':
                    result.setFontItalic(True)
                elif key == 'underline':
                    result.setUnderlineStyle(
                        QtGui.QTextCharFormat.SingleUnderline)
                elif key == 'sans':
                    result.setFontStyleHint(QtGui.QFont.SansSerif)
                elif key == 'roman':
                    result.setFontStyleHint(QtGui.QFont.Times)
                elif key == 'mono':
                    result.setFontStyleHint(QtGui.QFont.TypeWriter)
        return result 
Example 2
Project: IDAngr   Author: andreafioraldi   File: syntax.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format


# Syntax styles that can be shared by all languages 
Example 3
Project: MARA_Framework   Author: xtiankisutsa   File: sourcewindow.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _get_format_from_style(self, token, style):
        """ Returns a QTextCharFormat for token by reading a Pygments style.
        """
        result = QtGui.QTextCharFormat()
        for key, value in style.style_for_token(token).items():
            if value:
                if key == 'color':
                    result.setForeground(self._get_brush(value))
                elif key == 'bgcolor':
                    result.setBackground(self._get_brush(value))
                elif key == 'bold':
                    result.setFontWeight(QtGui.QFont.Bold)
                elif key == 'italic':
                    result.setFontItalic(True)
                elif key == 'underline':
                    result.setUnderlineStyle(
                        QtGui.QTextCharFormat.SingleUnderline)
                elif key == 'sans':
                    result.setFontStyleHint(QtGui.QFont.SansSerif)
                elif key == 'roman':
                    result.setFontStyleHint(QtGui.QFont.Times)
                elif key == 'mono':
                    result.setFontStyleHint(QtGui.QFont.TypeWriter)
        return result 
Example 4
Project: guppy-proxy   Author: roglew   File: hexteditor.py    License: MIT License 6 votes vote down vote up
def set_bytes(self, bs):
        with DisableUpdates(self.textedit):
            self.pretty_mode = False
            self.data = bs
            chunks = HextEditor._split_by_printables(bs)
            self.clear()
            cursor = QTextCursor(self.textedit.document())
            cursor.beginEditBlock()
            try:
                cursor.select(QTextCursor.Document)
                cursor.setCharFormat(QTextCharFormat())
                cursor.clearSelection()
                for chunk in chunks:
                    if chr(chunk[0]) in qtprintable:
                        cursor.insertText(chunk.decode())
                    else:
                        for b in chunk:
                            self._insert_byte(cursor, b)
            finally:
                cursor.endEditBlock()
        self.repaint() # needed to fix issue with py2app 
Example 5
Project: QualCoder   Author: ccbogel   File: cases.py    License: MIT License 6 votes vote down vote up
def highlight(self):
        """ Apply text highlighting to current file.
        Highlight text of selected case with red underlining.
        #format_.setForeground(QtGui.QColor("#990000")) """

        if self.selected_file is None:
            return
        if self.selected_file['fulltext'] is None:
            return
        format_ = QtGui.QTextCharFormat()
        cursor = self.ui.textBrowser.textCursor()
        for item in self.case_text:
            try:
                cursor.setPosition(int(item['pos0']), QtGui.QTextCursor.MoveAnchor)
                cursor.setPosition(int(item['pos1']), QtGui.QTextCursor.KeepAnchor)
                format_.setFontUnderline(True)
                format_.setUnderlineColor(QtCore.Qt.red)
                cursor.setCharFormat(format_)
            except:
                msg = "highlight, text length " + str(len(self.ui.textBrowser.toPlainText()))
                msg += "\npos0:" + str(item['pos0']) + ", pos1:" + str(item['pos1'])
                logger.debug(msg) 
Example 6
Project: QualCoder   Author: ccbogel   File: manage_files.py    License: MIT License 6 votes vote down vote up
def highlight(self, fid, textEdit):
        """ Add coding and annotation highlights. """
        cur = self.app.conn.cursor()
        sql = "select pos0,pos1 from annotation where fid=? union all select pos0,pos1 from code_text where fid=?"
        cur.execute(sql, [fid, fid])
        annoted_coded = cur.fetchall()
        format_ = QtGui.QTextCharFormat()
        format_.setFontFamily(self.app.settings['font'])
        format_.setFontPointSize(self.app.settings['fontsize'])

        # remove formatting
        cursor = textEdit.textCursor()
        cursor.setPosition(0, QtGui.QTextCursor.MoveAnchor)
        cursor.setPosition(len(textEdit.toPlainText()), QtGui.QTextCursor.KeepAnchor)
        cursor.setCharFormat(format_)
        # add formatting
        for item in annoted_coded:
            cursor.setPosition(int(item[0]), QtGui.QTextCursor.MoveAnchor)
            cursor.setPosition(int(item[1]), QtGui.QTextCursor.KeepAnchor)
            format_.setFontUnderline(True)
            format_.setUnderlineColor(QtCore.Qt.red)
            cursor.setCharFormat(format_) 
Example 7
Project: dcc   Author: amimo   File: sourcewindow.py    License: Apache License 2.0 5 votes vote down vote up
def _get_format(self, token):
        """ Returns a QTextCharFormat for token or None.
        """
        if token in self._formats:
            return self._formats[token]

        result = self._get_format_from_style(token, self._style)

        self._formats[token] = result
        return result 
Example 8
Project: easygui_qt   Author: aroberge   File: show_text_window.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QtGui.QTextCharFormat()
        keywordFormat.setForeground(QtCore.Qt.blue)
        keywordFormat.setFontWeight(QtGui.QFont.Bold)

        keywordPatterns = ["\\b{}\\b".format(k) for k in keyword.kwlist]

        self.highlightingRules = [(QtCore.QRegExp(pattern), keywordFormat)
                for pattern in keywordPatterns]

        classFormat = QtGui.QTextCharFormat()
        classFormat.setFontWeight(QtGui.QFont.Bold)
        self.highlightingRules.append((QtCore.QRegExp("\\bQ[A-Za-z]+\\b"),
                classFormat))

        singleLineCommentFormat = QtGui.QTextCharFormat()
        singleLineCommentFormat.setForeground(QtCore.Qt.gray)
        self.highlightingRules.append((QtCore.QRegExp("#[^\n]*"),
                singleLineCommentFormat))

        quotationFormat = QtGui.QTextCharFormat()
        quotationFormat.setForeground(QtCore.Qt.darkGreen)
        self.highlightingRules.append((QtCore.QRegExp("\".*\""),
                quotationFormat))
        self.highlightingRules.append((QtCore.QRegExp("'.*'"),
                quotationFormat)) 
Example 9
Project: Lector   Author: BasioMeusPuga   File: annotations.py    License: GNU General Public License v3.0 5 votes vote down vote up
def update_preview(self):
        cursor = self.parent.previewView.textCursor()
        cursor.setPosition(0)
        cursor.movePosition(QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)

        # TODO
        # Other kinds of text markup
        previewCharFormat = QtGui.QTextCharFormat()

        if self.foregroundCheck.isChecked():
            previewCharFormat.setForeground(self.foregroundColor)

        highlight = QtCore.Qt.transparent
        if self.highlightCheck.isChecked():
            highlight = self.highlightColor
        previewCharFormat.setBackground(highlight)

        font_weight = QtGui.QFont.Normal
        if self.boldCheck.isChecked():
            font_weight = QtGui.QFont.Bold
        previewCharFormat.setFontWeight(font_weight)

        if self.italicCheck.isChecked():
            previewCharFormat.setFontItalic(True)

        if self.underlineCheck.isChecked():
            previewCharFormat.setFontUnderline(True)
            previewCharFormat.setUnderlineColor(self.underlineColor)
            previewCharFormat.setUnderlineStyle(
                self.underline_styles[self.underlineType.currentText()])

        previewCharFormat.setFontStyleStrategy(
            QtGui.QFont.PreferAntialias)

        cursor.setCharFormat(previewCharFormat)
        cursor.clearSelection()
        self.parent.previewView.setTextCursor(cursor) 
Example 10
Project: Lector   Author: BasioMeusPuga   File: annotations.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.annotation_type = None
        self.annotation_components = None
        self.underline_styles = {
            'Solid': QtGui.QTextCharFormat.SingleUnderline,
            'Dashes': QtGui.QTextCharFormat.DashUnderline,
            'Dots': QtGui.QTextCharFormat.DotLine,
            'Wavy': QtGui.QTextCharFormat.WaveUnderline} 
Example 11
Project: Lector   Author: BasioMeusPuga   File: contentwidgets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def clear_annotations(self):
        if not self.are_we_doing_images_only:
            cursor = self.pw.textCursor()
            cursor.setPosition(0)
            cursor.movePosition(
                QtGui.QTextCursor.End, QtGui.QTextCursor.KeepAnchor)

            previewCharFormat = QtGui.QTextCharFormat()
            previewCharFormat.setFontStyleStrategy(
                QtGui.QFont.PreferAntialias)
            cursor.setCharFormat(previewCharFormat)
            cursor.clearSelection()
            self.pw.setTextCursor(cursor) 
Example 12
Project: CHATIMUSMAXIMUS   Author: benhoff   File: message_area.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, text_color=Qt.white, font=QtGui.QFont.DemiBold):
        super(_StandardTextFormat, self).__init__()
        self.setFontWeight(font)
        self.setForeground(text_color)
        self.setFontPointSize(13)
        self.setVerticalAlignment(QtGui.QTextCharFormat.AlignMiddle)


# TODO: see `QTextEdit.setAlignment` for setting the time to the right 
Example 13
Project: grap   Author: AirbusCyber   File: QtGrapSyntax.py    License: MIT License 5 votes vote down vote up
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    _color.setNamedColor(color)

    _format = QTextCharFormat()
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format 
Example 14
Project: execution-trace-viewer   Author: teemu-l   File: syntax_hl_log.py    License: MIT License 5 votes vote down vote up
def format(color, style=""):
    """Return a QTextCharFormat with the given attributes."""
    _color = QColor()
    _color.setNamedColor(color)
    _format = QTextCharFormat()
    _format.setForeground(_color)
    if "bold" in style:
        _format.setFontWeight(QFont.Bold)
    if "italic" in style:
        _format.setFontItalic(True)
    return _format


# Syntax styles 
Example 15
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def font(self, family):
        format = QtGui.QTextCharFormat()
        format.setFontFamily(family)
        self.MergeFormat(format) 
Example 16
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def PointSize(self, size):
        puntos = int(size)
        if puntos > 0:
            format = QtGui.QTextCharFormat()
            format.setFontPointSize(puntos)
            self.MergeFormat(format) 
Example 17
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Negrita(self):
        format = QtGui.QTextCharFormat()
        if self.actionNegrita.isChecked():
            format.setFontWeight(QtGui.QFont.Bold)
        else:
            format.setFontWeight(QtGui.QFont.Normal)
        self.MergeFormat(format) 
Example 18
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Cursiva(self):
        format = QtGui.QTextCharFormat()
        format.setFontItalic(self.actionCursiva.isChecked())
        self.MergeFormat(format) 
Example 19
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Subrayado(self):
        format = QtGui.QTextCharFormat()
        format.setFontUnderline(self.actionSubrayado.isChecked())
        self.MergeFormat(format) 
Example 20
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Superindice(self):
        if self.actionSubScript.isChecked():
            self.actionSubScript.blockSignals(True)
            self.actionSubScript.setChecked(False)
            self.actionSubScript.blockSignals(False)
        format = QtGui.QTextCharFormat()
        if self.actionSuperScript.isChecked():
            format.setVerticalAlignment(QtGui.QTextCharFormat.AlignSuperScript)
        else:
            format.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
        self.MergeFormat(format) 
Example 21
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def Subindice(self):
        if self.actionSuperScript.isChecked():
            self.actionSuperScript.blockSignals(True)
            self.actionSuperScript.setChecked(False)
            self.actionSuperScript.blockSignals(False)
        format = QtGui.QTextCharFormat()
        if self.actionSubScript.isChecked():
            format.setVerticalAlignment(QtGui.QTextCharFormat.AlignSubScript)
        else:
            format.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
        self.MergeFormat(format) 
Example 22
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def updateUI(self):
        """Update button status when cursor move"""
        self.fontComboBox.setCurrentIndex(self.fontComboBox.findText(
            self.notas.fontFamily()))
        self.FontColor.setPalette(QtGui.QPalette(self.notas.textColor()))
        self.FontSize.setCurrentIndex(self.FontSize.findText(
            str(int(self.notas.fontPointSize()))))
        self.actionNegrita.setChecked(
            self.notas.fontWeight() == QtGui.QFont.Bold)
        self.actionCursiva.setChecked(self.notas.fontItalic())
        self.actionSubrayado.setChecked(self.notas.fontUnderline())
        format = self.notas.currentCharFormat()
        self.actionTachado.setChecked(format.fontStrikeOut())
        self.actionSuperScript.setChecked(False)
        self.actionSubScript.setChecked(False)
        if format.verticalAlignment() == QtGui.QTextCharFormat.AlignSuperScript:
            self.actionSuperScript.setChecked(True)
        elif format.verticalAlignment() == QtGui.QTextCharFormat.AlignSubScript:
            self.actionSubScript.setChecked(True)
        self.actionAlinearIzquierda.setChecked(
            self.notas.alignment() == QtCore.Qt.AlignLeft)
        self.actionCentrar.setChecked(
            self.notas.alignment() == QtCore.Qt.AlignHCenter)
        self.actionJustificar.setChecked(
            self.notas.alignment() == QtCore.Qt.AlignJustify)
        self.actionAlinearDerecha.setChecked(
            self.notas.alignment() == QtCore.Qt.AlignRight) 
Example 23
Project: pychemqt   Author: jjgomera   File: texteditor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def colordialog(self):
        """Show dialog to choose font color"""
        dialog = QtWidgets.QColorDialog(self.notas.textColor(), self)
        if dialog.exec_():
            self.FontColor.setPalette(QtGui.QPalette(dialog.currentColor()))
            self.notas.setTextColor(dialog.currentColor())
            format = QtGui.QTextCharFormat()
            format.setForeground(dialog.currentColor())
            self.MergeFormat(format) 
Example 24
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, textFormat: Optional[Union[QTextCharFormat, Sequence[QTextCharFormat]]] = None,
                 matchPattern: Optional[QRegularExpression] = None) -> None:
        """
        :param textFormat: Text format of text mathched by pattern
        :param matchPattern: Regex pattern to match wanted text
        """

        super().__init__(None)

        self._text_format = textFormat
        self._match_pattern = matchPattern 
Example 25
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def text_format(self) -> Union[QTextCharFormat, Sequence[QTextCharFormat], None]:
        return self._text_format 
Example 26
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _setFormat(self, start: int, length: int, text_format: QTextCharFormat) -> None:
        self.setFormat(
            start,
            length,
            text_format
        ) 
Example 27
def _setupFormat(self, color: QColor, fontSettings: QFont, colorIsForeground: bool = True) -> QTextCharFormat:
        pattern_format = QTextCharFormat()
        if color and colorIsForeground:
            pattern_format.setForeground(color)
        if color and (not colorIsForeground):
            pattern_format.setBackground(color)
        pattern_format.setFontItalic(fontSettings.italic())
        pattern_format.setFontWeight(fontSettings.bold())

        return pattern_format 
Example 28
def _setupFormat(self, color: QColor) -> QTextCharFormat:
        pattern_format = QTextCharFormat()
        if color is not None:
            pattern_format.setForeground(color)
        pattern_format.setFontItalic(self._target.property("font").italic())
        pattern_format.setFontWeight(self._target.property("font").bold())

        return pattern_format 
Example 29
Project: eddy   Author: danielepantaleone   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fmt(color):
        """
        Return a QTextCharFormat with the given attributes.
        """
        _color = QtGui.QColor()
        _color.setNamedColor(color)
        _format = QtGui.QTextCharFormat()
        _format.setForeground(_color)
        return _format 
Example 30
Project: MARA_Framework   Author: xtiankisutsa   File: sourcewindow.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_format(self, token):
        """ Returns a QTextCharFormat for token or None.
        """
        if token in self._formats:
            return self._formats[token]

        result = self._get_format_from_style(token, self._style)

        self._formats[token] = result
        return result