It\'s my first time using stackoverflow to find an answer, to my problems. I\'m using a QtGui.QTextEdit to display text similar to below and would like to change the color o
This can be done quite easily with QSyntaxHighlighter. Here's a simple demo:
from PyQt4 import QtCore, QtGui
sample = """
--[ Begin
this is a test
[ERROR] this test failed.
--[ Command returned exit code 1
"""
class Highlighter(QtGui.QSyntaxHighlighter):
def __init__(self, parent):
super(Highlighter, self).__init__(parent)
self.sectionFormat = QtGui.QTextCharFormat()
self.sectionFormat.setForeground(QtCore.Qt.blue)
self.errorFormat = QtGui.QTextCharFormat()
self.errorFormat.setForeground(QtCore.Qt.red)
def highlightBlock(self, text):
# uncomment this line for Python2
# text = unicode(text)
if text.startswith('--['):
self.setFormat(0, len(text), self.sectionFormat)
elif text.startswith('[ERROR]'):
self.setFormat(0, len(text), self.errorFormat)
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.editor = QtGui.QTextEdit(self)
self.highlighter = Highlighter(self.editor.document())
self.editor.setText(sample)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.editor)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 150, 300, 300)
window.show()
sys.exit(app.exec_())