Python PyQt5.QtGui.QTextCharFormat() Examples

The following are code examples for showing how to use PyQt5.QtGui.QTextCharFormat(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: dcc   Author: amimo   File: sourcewindow.py    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: cct   Author: awacha   File: logviewer_text.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        logging.Handler.__init__(self)
        formatter = logging.Formatter('%(asctime)s: %(levelname)s: %(name)s: %(message)s')
        self.setFormatter(formatter)
        self.setupUi(self)
        self.debugformat = QtGui.QTextCharFormat()
        self.debugformat.setFontWeight(QtGui.QFont.Normal)
        self.debugformat.setForeground(QtCore.Qt.lightGray)
        self.warningformat = QtGui.QTextCharFormat()
        self.warningformat.setForeground(QtCore.Qt.darkYellow)
        self.errorformat = QtGui.QTextCharFormat()
        self.errorformat.setForeground(QtCore.Qt.red)
        self.criticalformat = QtGui.QTextCharFormat()
        self.criticalformat.setForeground(QtCore.Qt.black)
        self.criticalformat.setBackground(QtCore.Qt.red)
        self.infoformat = QtGui.QTextCharFormat() 
Example 3
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def superScript(self):
        """
        Allow to create the character super script
        """
        # Grab the current format
        fmt = self.text.currentCharFormat()

        # And get the vertical alignment property
        align = fmt.verticalAlignment()

        # Toggle the state
        if align == QtGui.QTextCharFormat.AlignNormal:
            fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSuperScript)
        else:
            fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)

        # Set the new format
        self.text.setCurrentCharFormat(fmt) 
Example 4
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def subScript(self):
        """
        Allow to create the character sub script
        """
        # Grab the current format
        fmt = self.text.currentCharFormat()

        # And get the vertical alignment property
        align = fmt.verticalAlignment()

        # Toggle the state
        if align == QtGui.QTextCharFormat.AlignNormal:
            fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSubScript)
        else:
            fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)

        # Set the new format
        self.text.setCurrentCharFormat(fmt) 
Example 5
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def insertURL(self, url, alias):
        """
        Executed to insert a URL in the description.
        :param url: the URL to insert
        :type url: str
        :param alias: the URL anchor text
        :type alias: str
        """
        linkFormat = QtGui.QTextCharFormat()
        linkFormat.setForeground(QtGui.QColor("blue"))
        linkFormat.setFont(self.text.currentFont())
        linkFormat.setFontPointSize(self.text.fontPointSize())
        linkFormat.setAnchorHref(url)
        linkFormat.setFontUnderline(True)
        linkFormat.setAnchor(True)
        linkFormat.setToolTip(url)
        cursor = self.text.textCursor()
        cursor.insertText(alias if alias else url, linkFormat)
        cursor.insertText(" ", self.defaultCharFormat) 
Example 6
Project: eddy   Author: obdasystems   File: description.py    GNU General Public License v3.0 6 votes vote down vote up
def insertWikiTag(self, wikiTagURL, wikiLabel):
        """
        Executed to insert a wiki tag.
        :param wikiTag: the wiki tag URL to insert
        :type wikiTagURL: str
        :param wikiLabel: the wiki tag label to insert
        :type wikiLabel: str
        """
        linkFormat = QtGui.QTextCharFormat()
        linkFormat.setForeground(QtGui.QColor("blue"))
        linkFormat.setFont(self.text.currentFont())
        linkFormat.setFontPointSize(self.text.fontPointSize())
        linkFormat.setFontUnderline(True)
        linkFormat.setAnchor(True)
        linkFormat.setAnchorHref(wikiTagURL)
        linkFormat.setToolTip(wikiTagURL)

        self.text.textCursor().insertText(wikiLabel, linkFormat)
        self.text.textCursor().insertText(" ", self.defaultCharFormat) 
Example 7
Project: IDAngr   Author: andreafioraldi   File: syntax.py    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 8
Project: mesoSPIM-control   Author: mesoSPIM   File: mesoSPIM_ScriptWindow.py    GNU General Public License v3.0 6 votes vote down vote up
def format(color, style=''):
    '''Return a QTextCharFormat with the given attributes.'''
    _color = QtGui.QColor()
    _color.setNamedColor(color)

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

    return _format


# Syntax styles that can be shared by all languages 
Example 9
Project: scm-workbench   Author: barry-scott   File: wb_diff_unified_view.py    Apache License 2.0 6 votes vote down vote up
def __init__( self, app, title ):
        super().__init__( app, title )

        self.code_font = self.app.codeFont()

        self.text_edit = QtWidgets.QTextEdit()

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget( self.text_edit )

        self.setLayout( self.layout )

        self.all_text_formats = {}
        for style, fg_colour, bg_colour in self.all_style_colours:
            char_format = QtGui.QTextCharFormat()
            char_format.setFont( self.code_font )
            char_format.setForeground( app.makeFgBrush( fg_colour ) )
            char_format.setBackground( app.makeBgBrush( bg_colour ) )
            self.all_text_formats[ style ] = char_format

        self.text_edit.setReadOnly( True )

        em = self.app.fontMetrics().width( 'm' )
        ex = self.app.fontMetrics().lineSpacing()
        self.resize( 130*em, 45*ex ) 
Example 10
Project: MARA_Framework   Author: xtiankisutsa   File: sourcewindow.py    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 11
Project: guppy-proxy   Author: roglew   File: hexteditor.py    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 12
Project: exostriker   Author: 3fon3fonov   File: syntax_py.py    MIT 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)
    if 'italicbold' in style:
        _format.setFontItalic(True)
        _format.setFontWeight(QFont.Bold)
    return _format 
Example 13
Project: Pl0-Compiler   Author: ericma15   File: Highlighter.py    MIT License 6 votes vote down vote up
def initializeFormats():
        baseFormat = QTextCharFormat()
        baseFormat.setFontFamily("courier")
        baseFormat.setFontPointSize(12)
        for name, color in (("normal", Qt.black),
                ("keyword", Qt.darkBlue), ("builtin", Qt.darkRed),
                ("constant", Qt.darkGreen),
                ("decorator", Qt.darkBlue), ("comment", Qt.darkGreen),
                ("string", Qt.darkYellow), ("number", Qt.darkMagenta),
                ("error", Qt.darkRed), ("pyqt", Qt.darkCyan)):
            format = QTextCharFormat(baseFormat)
            format.setForeground(QColor(color))
            if name in ("keyword", "decorator"):
                format.setFontWeight(QFont.Bold)
            if name == "comment":
                format.setFontItalic(True)
            Pl0Highlighter.Formats[name] = format 
Example 14
Project: pygwa   Author: cdd1969   File: syntaxPython.py    GNU General Public License v2.0 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 15
Project: MESmerize   Author: kushalkolar   File: syntax_editor.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        Formatter.__init__(self)
        self.data = []

        self.styles = {}
        for token, style in self.style:
            qtf = QTextCharFormat()

            if style['color']:
                qtf.setForeground(hex2QColor(style['color']))
            if style['bgcolor']:
                qtf.setBackground(hex2QColor(style['bgcolor']))
            if style['bold']:
                qtf.setFontWeight(QFont.Bold)
            if style['italic']:
                qtf.setFontItalic(True)
            if style['underline']:
                qtf.setFontUnderline(True)
            self.styles[str(token)] = qtf 
Example 16
Project: dcc   Author: amimo   File: sourcewindow.py    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 17
Project: cct   Author: awacha   File: scripteditor.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        QtGui.QSyntaxHighlighter.__init__(self, *args, **kwargs)
        self.keywordformat = QtGui.QTextCharFormat()
        self.keywordformat.setFontWeight(QtGui.QFont.Bold)
        self.keywordformat.setForeground(QtCore.Qt.darkMagenta)
        self.keywords_re = [re.compile(r'\b' + c.name + r'\b') for c in Command.allcommands()]
        self.commentformat = QtGui.QTextCharFormat()
        self.commentformat.setForeground(QtCore.Qt.lightGray)
        self.comment_re = re.compile('#.*$')
        self.labelformat = QtGui.QTextCharFormat()
        self.labelformat.setForeground(QtCore.Qt.blue)
        self.label_re = re.compile(r'^\s*\@.*$') 
Example 18
Project: cct   Author: awacha   File: scripteditor.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def onCommandStarted(self, linenumber: int):
        logger.debug('Command started on line {:d}'.format(linenumber))
        es = QtWidgets.QTextEdit.ExtraSelection()
        fmt = QtGui.QTextCharFormat()
        fmt.setBackground(QtGui.QBrush(QtCore.Qt.green))
        es.format = fmt
        cursor = QtGui.QTextCursor(self.document)
        cursor.movePosition(QtGui.QTextCursor.Start)
        cursor.movePosition(QtGui.QTextCursor.Down, QtGui.QTextCursor.MoveAnchor, linenumber)
        cursor.movePosition(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.MoveAnchor)
        cursor.movePosition(QtGui.QTextCursor.EndOfLine, QtGui.QTextCursor.KeepAnchor)
        cursor.select(QtGui.QTextCursor.LineUnderCursor)
        es.cursor = cursor
        self.scriptEdit.setExtraSelections([es]) 
Example 19
Project: Lector   Author: BasioMeusPuga   File: annotations.py    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 20
Project: Lector   Author: BasioMeusPuga   File: annotations.py    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 21
Project: Lector   Author: BasioMeusPuga   File: contentwidgets.py    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 22
Project: eddy   Author: obdasystems   File: log.py    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 23
Project: data-structure   Author: yunowo   File: search_highlighter.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent, counter):
        super(SearchHighlighter, self).__init__(parent)
        self.counter = counter

        hf = QTextCharFormat()
        hf.setBackground(Qt.yellow)
        self.highlight_format = hf
        self.match_case = True
        self.only_words = True
        self.regex = False
        self.patterns = []
        self.results = [] 
Example 24
Project: notepad   Author: lfsando   File: notepad.py    GNU General Public License v3.0 5 votes vote down vote up
def highlight_matches(self, results):
        print(results)
        pass
        #class Match()
        #selected = QtGui.QTextCharFormat()



    # ACTIONS 
Example 25
Project: notepad   Author: lfsando   File: highlighter.py    GNU General Public License v3.0 5 votes vote down vote up
def format(color, style=''):

    word_color = QColor()
    word_color.setNamedColor(color)
    word_format = QTextCharFormat()
    word_format.setForeground(word_color)
    if 'italic' in style:
        word_format.setFontItalic(True)
    elif 'bold' in style:
        word_format.setFontWeight(QFont.Bold)

    return word_format 
Example 26
Project: grap   Author: AirbusCyber   File: QtGrapSyntax.py    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 27
Project: PyMima   Author: ahui2016   File: passwordedit.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)

        self.numberFormat = QTextCharFormat()
        self.numberFormat.setFontWeight(QFont.Bold)
        self.numberFormat.setForeground(Qt.red) 
Example 28
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    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 29
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    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 30
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: syntax_highlighter.py    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 31
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: exp_syntax_highlighter.py    GNU General Public License v3.0 5 votes vote down vote up
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 32
Project: VUT-FIT-IFJ-2017-toolkit   Author: thejoeejoee   File: formatted_text_writer.py    GNU General Public License v3.0 5 votes vote down vote up
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 33
Project: scm-workbench   Author: barry-scott   File: wb_logging.py    Apache License 2.0 5 votes vote down vote up
def initStyles( self ):
        if self.app.isDarkMode():
            all_style_colours = self.all_style_colours_dark_mode

        else:
            all_style_colours = self.all_style_colours_light_mode

        self.all_text_formats = {}
        for style, fg_colour, bg_colour in all_style_colours:
            fmt = QtGui.QTextCharFormat()
            fmt.setForeground( self.app.makeFgBrush( fg_colour ) )
            fmt.setBackground( self.app.makeBgBrush( bg_colour ) )
            self.all_text_formats[ style ] = fmt 
Example 34
Project: eddy   Author: danielepantaleone   File: log.py    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 35
Project: MARA_Framework   Author: xtiankisutsa   File: sourcewindow.py    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 
Example 36
Project: Pl0-Compiler   Author: ericma15   File: Main.py    MIT License 5 votes vote down vote up
def highlightCurrentLine(self, line, status):
        try:
            selection = self.sourceCodePlainTextEdit.document().findBlockByLineNumber(line)
            cursor = self.sourceCodePlainTextEdit.textCursor()
            line = selection.text() + " "
            cursor.setPosition(selection.position())
            cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
            formats = QTextCharFormat()
            if status:
                formats.setBackground(QColor('red'))
            cursor.removeSelectedText()
            cursor.insertText(line, formats)
        except:
            print(traceback.format_exc()) 
Example 37
Project: PyQt   Author: PyQt5   File: HighlightText.py    GNU General Public License v3.0 5 votes vote down vote up
def highlight(self):
        text = self.findText.text()  # 输入框中的文字
        if not text:
            return
        col = QColorDialog.getColor(self.textEdit.textColor(), self)
        if not col.isValid():
            return
        fmt = QTextCharFormat()
        fmt.setForeground(col)
        # 先把光标移动到开头
        self.textEdit.moveCursor(QTextCursor.Start)
        while self.textEdit.find(text, QTextDocument.FindWholeWords):  # 查找所有文字
            self.mergeFormatOnWordOrSelection(fmt) 
Example 38
Project: PyQt   Author: PyQt5   File: CalendarQssStyle.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(CalendarWidget, self).__init__(*args, **kwargs)
        # 隐藏左边的序号
        self.setVerticalHeaderFormat(self.NoVerticalHeader)

        # 修改周六周日颜色

        fmtGreen = QTextCharFormat()
        fmtGreen.setForeground(QBrush(Qt.green))
        self.setWeekdayTextFormat(Qt.Saturday, fmtGreen)

        fmtOrange = QTextCharFormat()
        fmtOrange.setForeground(QBrush(QColor(252, 140, 28)))
        self.setWeekdayTextFormat(Qt.Sunday, fmtOrange) 
Example 39
Project: harshark   Author: MacroPolo   File: generic.py    MIT License 5 votes vote down vote up
def clearTabSearch(app, tab_group='all'):
    colour_default_hex = app.config.getConfig('colour_scheme')['default']
    colour_default = QColor(colour_default_hex)

    eraser = QTextCharFormat()
    eraser.setBackground(QBrush(colour_default))

    if tab_group == 'request':
        tabs = app.request_textedits
        app.statusbar.clearMessage()
        app.clear_match_request_btn.setEnabled(False)
        app.next_match_request_btn.setEnabled(False)
    elif tab_group == 'response':
        tabs = app.response_textedits
        app.clear_match_response_btn.setEnabled(False)
        app.next_match_response_btn.setEnabled(False)
    else:
        tabs = app.request_textedits + app.response_textedits
        app.statusbar.clearMessage()
        app.clear_match_request_btn.setEnabled(False)
        app.next_match_request_btn.setEnabled(False)
        app.clear_match_response_btn.setEnabled(False)
        app.next_match_response_btn.setEnabled(False)

    for tab in tabs:
        tab.selectAll()
        cursor = tab.textCursor()
        cursor.mergeCharFormat(eraser)
        tab.moveCursor(QTextCursor.Start) 
Example 40
Project: harshark   Author: MacroPolo   File: subsearch.py    MIT License 5 votes vote down vote up
def __init__(self, app, tab_group):
        self.app = app
        self.tab_group = tab_group
        self.matches = []
        self.highlight_style = QTextCharFormat()
        self.main() 
Example 41
Project: spyrit   Author: pvaret   File: OutputManager.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__( self, world, textview ):

    self.world = world
    self.view_settings  = world.settings._ui._view

    self.textview = textview

    self.textcursor = QTextCursor( textview.document() )

    self.textformat = QTextCharFormat()
    self.infoformat = QTextCharFormat()

    self.textformatmanager = FormatStack( QTextFormatFormatter( self.textformat ) )
    self.infoformatmanager = FormatStack( QTextFormatFormatter( self.infoformat ) )

    self.textformatmanager.setBaseFormat( self.view_settings._font._text_format )
    self.infoformatmanager.setBaseFormat( self.view_settings._font._info_format )

    self.view_settings.onChange( "font.text_format",
                                 self.textformatmanager.setBaseFormat )
    self.view_settings.onChange( "font.info_format",
                                 self.infoformatmanager.setBaseFormat )

    self.searchmanager = SearchManager( textview, world.settings )

    self.was_connected   = False
    self.pending_newline = False

    self.refresh()
    self.setWordWrapping()

    for key in [ "font.name", "font.size", "background.color" ]:
      self.view_settings.onChange( key, self.refresh )

    self.view_settings.onChange( "wrap_column", self.setWordWrapping )

    self.textview.setSplitScrollback( self.view_settings[ "split_scroll" ] )
    self.textview.setPaging( self.view_settings[ "paging" ] )

    self.view_settings.onChange( "split_scroll", self.textview.setSplitScrollback )
    self.view_settings.onChange( "paging",       self.textview.setPaging ) 
Example 42
Project: deen   Author: takeshixx   File: encoder.py    Apache License 2.0 5 votes vote down vote up
def search_highlight(self):
        """The function that will be called whenever the
        search area is submitted. It will search within
        the text_field and highlights matches."""
        cursor = self.text_field.textCursor()
        char_format = QTextCharFormat()
        cursor.select(QTextCursor.Document)
        cursor.mergeCharFormat(char_format)
        cursor.clearSelection()
        char_format.setBackground(QBrush(QColor('yellow')))
        regex = QRegularExpression(self.ui.search_area.text())
        matches = regex.globalMatch(self.text_field.toPlainText())
        _matches = []
        while matches.hasNext():
            _matches.append(matches.next())
        self.search_matches = _matches
        self.ui.search_matches_label.setText('Matches: ' + str(len(self.search_matches)))
        self.ui.search_progress_bar.setRange(0, len(self.search_matches))
        if len(self.search_matches) > 100:
            self.ui.search_progress_bar.show()
        match_count = 1
        for match in self.search_matches:
            if match_count > 1000:
                # TODO: implement proper handling of > 1000 matches
                break
            self.ui.search_progress_bar.setValue(match_count)
            match_count += 1
            cursor.setPosition(match.capturedStart())
            cursor.setPosition(match.capturedEnd(), QTextCursor.KeepAnchor)
            cursor.mergeCharFormat(format)
        self.ui.search_progress_bar.hide() 
Example 43
Project: deen   Author: takeshixx   File: encoder.py    Apache License 2.0 5 votes vote down vote up
def clear_search_highlight(self, widget=None):
        """Reset any highlights set by the search
        function."""
        widget = widget or self
        cursor = self.text_field.textCursor()
        cursor.select(QTextCursor.Document)
        char_format = QTextCharFormat()
        cursor.setCharFormat(char_format)
        widget.ui.search_area.clear()
        widget.ui.search_matches_label.setText('Matches: 0') 
Example 44
Project: deen   Author: takeshixx   File: hex.py    Apache License 2.0 5 votes vote down vote up
def selection_changed(self):
        # Check if items from the previous selection
        # are still selected.
        for sel in self.current_selection:
            _widget = self.item(sel[0], sel[1])
            if not _widget.isSelected() and not _widget in self.selectedItems():
                self.current_selection.remove(sel)
                ascii_widget = self.cellWidget(sel[0], self.columnCount() - 1)
                cursor = ascii_widget.textCursor()
                cursor.select(QTextCursor.Document)
                cursor.setCharFormat(QTextCharFormat())
                cursor.clearSelection()
                ascii_widget.setTextCursor(cursor)
        for i in self.selectedItems():
            if not (i.row(), i.column()) in self.current_selection:
                self.current_selection.append((i.row(), i.column()))
            ascii_widget = self.cellWidget(i.row(), self.columnCount() - 1)
            cursor = ascii_widget.textCursor()
            char_format = QTextCharFormat()
            cursor.select(QTextCursor.Document)
            cursor.mergeCharFormat(char_format)
            cursor.clearSelection()
            char_format.setBackground(QBrush(QColor('darkCyan')))
            cursor.setPosition(i.column())
            cursor.setPosition(i.column() + 1, QTextCursor.KeepAnchor)
            cursor.mergeCharFormat(char_format) 
Example 45
Project: Lector   Author: BasioMeusPuga   File: annotations.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, parent=None):
        super(AnnotationsUI, self).__init__()
        self.setupUi(self)

        self.parent = parent
        self._translate = QtCore.QCoreApplication.translate

        # Current annotation
        self.modelIndex = None  # The index of the annotations list model in the parent dialog
        self.current_annotation = {}

        # Populate annotation type
        textmarkup_string = self._translate('AnnotationsUI', 'Text markup')
        all_types = [textmarkup_string]
        for i in all_types:
            self.typeBox.addItem(i)

        # Init defaults
        self.default_stylesheet = self.foregroundCheck.styleSheet()
        self.foregroundColor = QtGui.QColor.fromRgb(0, 0, 0)
        self.underlineColor = QtGui.QColor.fromRgb(255, 0, 0)
        self.highlightColor = QtGui.QColor.fromRgb(66, 209, 56)
        self.underline_styles = {
            'Solid': QtGui.QTextCharFormat.SingleUnderline,
            'Dashes': QtGui.QTextCharFormat.DashUnderline,
            'Dots': QtGui.QTextCharFormat.DotLine,
            'Wavy': QtGui.QTextCharFormat.WaveUnderline}

        # Push buttons
        self.foregroundColorButton.clicked.connect(self.modify_annotation)
        self.highlightColorButton.clicked.connect(self.modify_annotation)
        self.underlineColorButton.clicked.connect(self.modify_annotation)

        self.okButton.clicked.connect(self.ok_pressed)
        self.cancelButton.clicked.connect(self.hide)

        # Underline combo box
        underline_items = ['Solid', 'Dashes', 'Dots', 'Wavy']
        self.underlineType.addItems(underline_items)
        self.underlineType.currentIndexChanged.connect(self.modify_annotation)

        # Text markup related checkboxes
        self.foregroundCheck.clicked.connect(self.modify_annotation)
        self.highlightCheck.clicked.connect(self.modify_annotation)
        self.boldCheck.clicked.connect(self.modify_annotation)
        self.italicCheck.clicked.connect(self.modify_annotation)
        self.underlineCheck.clicked.connect(self.modify_annotation) 
Example 46
Project: Lector   Author: BasioMeusPuga   File: annotations.py    GNU General Public License v3.0 4 votes vote down vote up
def format_text(self, cursor, start_here, end_here):
        # This is applicable only to the PliantQTextBrowser
        # for the text_markup style of annotation

        # The cursor is the textCursor of the QTextEdit
        # containing the text that has to be modified

        if not self.annotation_components:
            return

        cursor.setPosition(start_here)
        cursor.setPosition(end_here, QtGui.QTextCursor.KeepAnchor)

        newCharFormat = QtGui.QTextCharFormat()

        if 'foregroundColor' in self.annotation_components:
            newCharFormat.setForeground(
                self.annotation_components['foregroundColor'])

        if 'highlightColor' in self.annotation_components:
            newCharFormat.setBackground(
                self.annotation_components['highlightColor'])

        if 'bold' in self.annotation_components:
            newCharFormat.setFontWeight(QtGui.QFont.Bold)

        if 'italic' in self.annotation_components:
            newCharFormat.setFontItalic(True)

        if 'underline' in self.annotation_components:
            newCharFormat.setFontUnderline(True)
            newCharFormat.setUnderlineStyle(
                self.underline_styles[self.annotation_components['underline'][0]])
            newCharFormat.setUnderlineColor(
                self.annotation_components['underline'][1])

        newCharFormat.setFontStyleStrategy(
            QtGui.QFont.PreferAntialias)

        cursor.setCharFormat(newCharFormat)
        cursor.clearSelection()
        return cursor 
Example 47
Project: napari-core   Author: napari   File: editor.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(Qt.darkBlue)
        keywordFormat.setFontWeight(QFont.Bold)

        keywordPatterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b",
                "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b",
                "\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b",
                "\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b",
                "\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b",
                "\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b",
                "\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b",
                "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b",
                "\\bvolatile\\b"]

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

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

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.red)
        self.highlightingRules.append((QRegExp("//[^\n]*"),
                singleLineCommentFormat))

        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
                functionFormat))

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")