我如何才能找到一个子,并强调它的QTextEdit?(How can I find a substr

2019-07-17 11:40发布

我有一个QTextEdit窗口,显示了文件的内容。 我希望能够找到使用正则表达式文本中的所有比赛,并通过使比赛背景不同或改变比赛的文字颜色或使其大胆要么突出显示它们。 我怎样才能做到这一点?

Answer 1:

我觉得你的问题最简单的解决方法是使用关联到你的编辑光标为了做格式化。 这样你就可以设置前景色,背景,字体样式...以下示例标志着具有不同背景的匹配。

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

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



Answer 2:

这里是你如何可以突出显示文本样本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_())


文章来源: How can I find a substring and highlight it in QTextEdit?