Skip to content

CodeSyntaxHighlight#

A code highlighter subclass of QSyntaxHighlighter that can be used to highlight code in a QTextEdit.

Code lexer and available styles are from pygments python library

List of available languages are available here.

List of available styles are available here.

Example#

from qtpy.QtGui import QColor, QPalette
from qtpy.QtWidgets import QApplication, QTextEdit

from superqt.utils import CodeSyntaxHighlight

app = QApplication([])

text_area = QTextEdit()

highlight = CodeSyntaxHighlight(text_area.document(), "python", "monokai")

palette = text_area.palette()
palette.setColor(QPalette.Base, QColor(highlight.background_color))
text_area.setPalette(palette)
text_area.setText(
    """from argparse import ArgumentParser

def main():
    parser = ArgumentParser()
    parser.add_argument("name", help="Your name")
    args = parser.parse_args()
    print(f"Hello {args.name}")


if __name__ == "__main__":
    main()
"""
)

text_area.show()
text_area.resize(400, 200)

app.exec_()

CodeSyntaxHighlight

Qt Class#

QSyntaxHighlighter

Methods#

A syntax highlighter for code using Pygments.

Parameters:

Name Type Description Default
parent QTextDocument | QObject | None

The parent object. Usually a QTextDocument. To use this class with a QTextArea, pass in text_area.document().

required
lang str

The language of the code to highlight. This should be a string that Pygments recognizes, e.g. 'python', 'pytb', 'cpp', 'java', etc.

required
theme KnownStyle | str

The name of the Pygments style to use. For a complete list of available styles, use pygments.styles.get_all_styles().

'default'

Examples:

from qtpy.QtWidgets import QTextEdit
from superqt.utils import CodeSyntaxHighlight

text_area = QTextEdit()
highlighter = CodeSyntaxHighlight(text_area.document(), "python", "monokai")

# then manually apply the background color to the text area.
palette = text_area.palette()
bgrd_color = QColor(self._highlight.background_color)
palette.setColor(QPalette.ColorRole.Base, bgrd_color)
text_area.setPalette(palette)

background_color: str property #

setLanguage(lang: str) -> None #

Set the language for the syntax highlighting.

This should be a string that Pygments recognizes, e.g. 'python', 'pytb', 'cpp', 'java', etc.

setTheme(theme: KnownStyle | str) -> None #

Set the theme for the syntax highlighting.

This should be a string that Pygments recognizes, e.g. 'monokai', 'solarized'. Use pygments.styles.get_all_styles() to see a list of available styles.