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

后端 未结 2 430
甜味超标
甜味超标 2021-01-15 20:15

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

2条回答
  •  梦毁少年i
    2021-01-15 20:39

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

提交回复
热议问题