如何找到子字符串并在QTextEdit中突出显示它?

时间:2012-12-20 22:52:45

标签: python regex qt pyqt pyside

我有一个QTextEdit窗口,显示文件的内容。 我希望能够使用正则表达式找到文本中的所有匹配项,并通过使匹配背景不同或通过更改匹配文本颜色或使其变为粗体来突出显示它们。我怎么能这样做?

2 个答案:

答案 0 :(得分:8)

我认为对您的问题最简单的解决方案是使用与编辑器关联的光标来进行格式化。这样您就可以设置前景,背景,字体样式......以下示例使用不同的背景标记匹配。

from PyQt4 import QtGui
from PyQt4 import QtCore

class MyHighlighter(QtGui.QTextEdit):
    def __init__(self, parent=None):
        super(MyHighlighter, self).__init__(parent)
        # Setup the text editor
        text = """In this text I want to highlight this word and only this word.\n""" +\
        """Any other word shouldn't be highlighted"""
        self.setText(text)
        cursor = self.textCursor()
        # Setup the desired format for matches
        format = QtGui.QTextCharFormat()
        format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
        # Setup the regex engine
        pattern = "word"
        regex = QtCore.QRegExp(pattern)
        # Process the displayed document
        pos = 0
        index = regex.indexIn(self.toPlainText(), pos)
        while (index != -1):
            # Select the matched text and apply the desired format
            cursor.setPosition(index)
            cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
            cursor.mergeCharFormat(format)
            # Move to the next match
            pos = index + regex.matchedLength()
            index = regex.indexIn(self.toPlainText(), pos)

if __name__ == "__main__":
    import sys
    a = QtGui.QApplication(sys.argv)
    t = MyHighlighter()
    t.show()
    sys.exit(a.exec_())

代码是不言自明的,但如果您有任何问题,请问他们。

答案 1 :(得分:5)

以下是如何在QTextEdit中突出显示文字的示例:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class highlightSyntax(QSyntaxHighlighter):
    def __init__(self, listKeywords, parent=None):
        super(highlightSyntax, self).__init__(parent)
        brush   = QBrush(Qt.darkBlue, Qt.SolidPattern)
        keyword = QTextCharFormat()
        keyword.setForeground(brush)
        keyword.setFontWeight(QFont.Bold)

        self.highlightingRules = [  highlightRule(QRegExp("\\b" + key + "\\b"), keyword)
                                    for key in listKeywords
                                    ]

    def highlightBlock(self, text):
        for rule in self.highlightingRules:
            expression = QRegExp(rule.pattern)
            index      = expression.indexIn(text)

            while index >= 0:
              length = expression.matchedLength()
              self.setFormat(index, length, rule.format)
              index = text.indexOf(expression, index + length)

        self.setCurrentBlockState(0)  

class highlightRule(object):
    def __init__(self, pattern, format):
        self.pattern = pattern
        self.format  = format

class highlightTextEdit(QTextEdit):
    def __init__(self, fileInput, listKeywords, parent=None):
        super(highlightTextEdit, self).__init__(parent)
        highlightSyntax(QStringList(listKeywords), self)

        with open(fileInput, "r") as fInput:
            self.setPlainText(fInput.read())        

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = highlightTextEdit("/path/to/file", ["foo", "bar", "baz"])
    main.show()
    sys.exit(app.exec_())