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_())
def do_find_highlight(self, pattern):
cursor = self.editor.textCursor()
# Setup the desired format for matches
format = QTextCharFormat()
format.setBackground(QBrush(QColor("red")))
# Setup the regex engine
re = QRegularExpression(pattern)
i = re.globalMatch(self.editor.toPlainText()) # QRegularExpressionMatchIterator
# iterate through all the matches and highlight
while i.hasNext():
match = i.next() #QRegularExpressionMatch
# Select the matched text and apply the desired format
cursor.setPosition(match.capturedStart(), QTextCursor.MoveAnchor)
cursor.setPosition(match.capturedEnd(), QTextCursor.KeepAnchor)
cursor.mergeCharFormat(format)
3条答案
按热度按时间r6l8ljro1#
我认为最简单的解决方案是使用光标关联到您的编辑器,以便做格式化。这样您就可以设置前景,背景,字体样式……下面的示例用不同的背景标记匹配项。
代码是不言自明的,但如果你有任何问题,只是问他们。
8tntrjer2#
以下是如何在
QTextEdit
中突出显示文本的示例:fcipmucu3#
QT5更新了RegEx,参见QRegularExpressionhttps://dangelog.wordpress.com/2012/04/07/qregularexpression/
我更新了第一个使用游标的示例。
请注意以下更改:
1.这并不包含编辑,而是使用内部的编辑框,它可以很容易地更改为允许您传入编辑小部件。
1.这是一个正确的正则表达式查找,而不仅仅是一个单词。