Mark Mark - 1 month ago 13
Python Question

QtGui.QTextEdit set line color baced on what text the line contains

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 of the text on some lines based on if they contain certain text.

lines that start with --[ will be blue and lines that contain [ERROR] would be red.
I currently have something like the following,

from PyQt4 import QtCore, QtGui, uic
import sys

class Log(QtGui.QWidget):
def __init__(self, path=None, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.taskLog = QtGui.QTextEdit()
self.taskLog.setLineWrapMode(False)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.taskLog)
self.setLayout(vbox)

log = open("/net/test.log", 'r')
self.taskLog.setText(log.read())
log.close()


app = QtGui.QApplication(sys.argv)
wnd = Log()
wnd.show()
sys.exit(app.exec_())


The text looks something like this at the moment

--[ Begin
this is a test

[ERROR] this test failed.

--[ Command returned exit code 1


Hopefully you all will be able to help me work this out a lot faster that, trying to work it out my self.

Thanks,
Mark

Answer

This can be done quite easily with QSyntaxHighlighter. Here's a simple demo:

screenshot

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_())
Comments