QtGui.QTextEdit根据行包含的文本设置行颜色

2024-10-02 14:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次使用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_())

文本现在看起来像这样

^{pr2}$

希望你们能帮助我更快地解决这个问题,试着自己解决问题。在

谢谢, 马克


Tags: 文本importselfnoneloginitsysparent
2条回答

您可以使用HTML格式来实现这一点

textEdit.setHtml(text);

但更好的是,QSyntaxHighlighter类:

文件:http://doc.qt.io/qt-5/qsyntaxhighlighter.html

Python示例:https://wiki.python.org/moin/PyQt/Python%20syntax%20highlighting

这里是一个带有代码编辑器的示例。在

^{pr2}$

这可以很容易地用QSyntaxHighlighter完成。下面是一个简单的演示:

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

相关问题 更多 >