This wiki is in the process of being archived due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies. Edits are discouraged.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

If you need a code editor with syntax highlighting, but don't want something as heavyweight as QsciScintilla, you can use the QSyntaxHighlighter class to apply highlighting to a QPlainTextEdit widget.

This example was based on existing work by Carson Farmer and Christophe Kibleur, and an example on the SciPres wiki. One aspect not addressed by this prior work is handling of Python's triple-quoted strings, which may span multiple lines; the QSyntaxHighlighter documentation includes an example for C++ comments, but those have different beginning and ending delimiters /* ... */, whereas Python's triple-quoted strings have the same delimiter at the beginning and end. These are handled by the match_multiline method and by treating the triple-quotes within strings as an special case --there may be an easier way to do this, but it seems to work pretty well.

I have placed this code under the Modified BSD License because I believe the author intended it to be freely used. However, I don't believe that I originally wrote this example, though I was responsible for migrating it to the Python Wiki. -- DavidBoddie 2017-01-19 20:34:17

I modified this code to fix a problem when triple-quotes were embedded inside strings. -- Artemio Garza Reyna 2021-08-08 20:26:00

   1 # syntax.py
   2 
   3 import sys
   4 
   5 from PySide2 import QtCore, QtGui, QtWidgets
   6 
   7 def format(color, style=''):
   8     """Return a QTextCharFormat with the given attributes.
   9     """
  10     _color = QtGui.QColor()
  11     _color.setNamedColor(color)
  12 
  13     _format = QtGui.QTextCharFormat()
  14     _format.setForeground(_color)
  15     if 'bold' in style:
  16         _format.setFontWeight(QtGui.QFont.Bold)
  17     if 'italic' in style:
  18         _format.setFontItalic(True)
  19 
  20     return _format
  21 
  22 
  23 # Syntax styles that can be shared by all languages
  24 STYLES = {
  25     'keyword': format('blue'),
  26     'operator': format('red'),
  27     'brace': format('darkGray'),
  28     'defclass': format('black', 'bold'),
  29     'string': format('magenta'),
  30     'string2': format('darkMagenta'),
  31     'comment': format('darkGreen', 'italic'),
  32     'self': format('black', 'italic'),
  33     'numbers': format('brown'),
  34 }
  35 
  36 
  37 class PythonHighlighter (QtGui.QSyntaxHighlighter):
  38     """Syntax highlighter for the Python language.
  39     """
  40     # Python keywords
  41