QtGui.QTextEdit根据行包含的文本设置行颜色
问题内容:
这是我第一次使用stackoverflow来找到问题的答案。我正在使用QtGui.QTextEdit来显示类似于以下内容的文本,并希望根据某些行中是否包含某些文本来更改文本的颜色。
以-[开头的行将为蓝色,而包含[ERROR]的行将为红色。我目前有类似以下的内容,
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_())
文本目前看起来像这样
--[ Begin
this is a test
[ERROR] this test failed.
--[ Command returned exit code 1
希望大家能够帮助我更快地完成这项工作,并努力实现自己。
谢谢马克
问题答案:
使用QSyntaxHighlighter可以很容易地做到这一点。这是一个简单的演示:
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_())