如何在 QTextEdit 中找到子字符串并突出显示它? [英] How can I find a substring and highlight it in QTextEdit?

查看:39
本文介绍了如何在 QTextEdit 中找到子字符串并突出显示它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a QTextEdit window that shows the content of a file. I would like to be able to find all matches inside the text using a regex and highlight them either by making the match background different or by changing the match text color or making it bold. How can I do this?

推荐答案

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

I think the simplest solution to your problem is to use the cursor associated to your editor in order to do the formatting. This way you can set the foreground, the background, the font style... The following example marks the matches with a different background.

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

代码一目了然,但如果您有任何问题,请直接问他们.

The code is self-explanatory but if you have any questions just ask them.

这篇关于如何在 QTextEdit 中找到子字符串并突出显示它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆