我认为最简单的解决方案是使用与您的编辑器关联的光标进行格式化。这样,您可以设置前景,背景,字体样式…下面的示例用不同的背景标记匹配项。
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_())
该代码是不言自明的,但是如果您有任何疑问,请问他们。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)