tpieciak
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():
return
endBlock = QtGui.QTextBlock()
if added > removed:
endBlock = doc.findBlock(position + added)
else:
endBlock = block
while block.isValid() and not (endBlock < block):
self.highlightBlock(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]
overrides.append(range)
i = text.indexOf(expression, i + expression.matchedLength())
layout.setAdditionalFormats(overrides)
block.document().markContentsDirty(block.position( ), block.length())
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():
return
endBlock = QtGui.QTextBlock()
if added > removed:
endBlock = doc.findBlock(position + added)
else:
endBlock = block
while block.isValid() and not (endBlock < block):
self.highlightBlock(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]
overrides.append(range)
i = text.indexOf(expression, i + expression.matchedLength())
layout.setAdditionalFormats(overrides)
block.document().markContentsDirty(block.position( ), block.length())