View Full Version : SyntaxHighlighter problem

1st September 2008, 06:13
I have found some code of syntax highlight in PyQt4, but my problem is that QTextEdit colorize text, but only first line, and only line when I put enter at the end of line at the following lines. If I open file with code, only first line is colorized. Rest of code is black.

Would you be so kind to help me?

class Highlighter(QtCore.QObject):
def __init__(self, parent=None):
QtCore.QObject.__init__(self, parent)

self.mappings = {}

def addToDocument(self, doc):
self.connect(doc, QtCore.SIGNAL("contentsChange(int, int, int)"), self.highlight)

def addMapping(self, pattern, format):
self.mappings[pattern] = format

def highlight(self, position, removed, added):
doc = self.sender()

block = doc.findBlock(position)
if not block.isValid():

endBlock = QtGui.QTextBlock()
if added > removed:
endBlock = doc.findBlock(position + added)
endBlock = block

while block.isValid() and not (endBlock < block):
block = block.next()

def highlightBlock(self, block):
layout = block.layout()
text = block.text()

overrides = []

for pattern in self.mappings:
expression = QtCore.QRegExp(pattern)
i = text.indexOf(expression)
while i >= 0:
range = QtGui.QTextLayout.FormatRange()
range.start = i
range.length = expression.matchedLength()
range.format = self.mappings[pattern]

i = text.indexOf(expression, i + expression.matchedLength())

block.document().markContentsDirty(block.position( ), block.length())

1st September 2008, 07:13
Why not use QSyntaxHighlighter?