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

发布于 2021-01-29 16:15:27

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

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看