您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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

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

其他 2022/1/1 18:43:19 有429人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶