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

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

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

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

from PyQt4 import QtGuifrom PyQt4 import QtCoreclass 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_())

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5662014.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存