How can I find a substring and highlight it in QTextEdit?

前端 未结 2 650
天命终不由人
天命终不由人 2021-01-02 21:59

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 th

2条回答
  •  伪装坚强ぢ
    2021-01-02 22:31

    Here is a sample of how can you highlight text in a 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_())
    

提交回复
热议问题