Skip to content

Commit de452f9

Browse files
committed
修复高亮问题
1 parent 3d210e4 commit de452f9

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

QTextEdit/HighlightText.py

+27-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import sys
2+
from PyQt5.QtCore import QRegExp
23
from PyQt5.QtGui import QTextCharFormat, QTextDocument, QTextCursor
34
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit,
45
QToolBar, QLineEdit, QPushButton, QColorDialog, QHBoxLayout, QWidget)
@@ -22,30 +23,46 @@ def __init__(self, parent=None):
2223

2324
tb = QToolBar(self)
2425
tb.addWidget(widget)
26+
self.addToolBar(tb)
2527

2628
def setText(self, text):
2729
self.textEdit.setPlainText(text)
2830

29-
def mergeFormatOnWordOrSelection(self, format):
30-
cursor = self.textEdit.textCursor()
31-
if not cursor.hasSelection():
32-
cursor.select(QTextCursor.WordUnderCursor)
33-
cursor.mergeCharFormat(format)
34-
self.textEdit.mergeCurrentCharFormat(format)
35-
3631
def highlight(self):
3732
text = self.findText.text() # 输入框中的文字
3833
if not text:
3934
return
35+
4036
col = QColorDialog.getColor(self.textEdit.textColor(), self)
4137
if not col.isValid():
4238
return
39+
40+
# 恢复默认的颜色
41+
cursor = self.textEdit.textCursor()
42+
cursor.select(QTextCursor.Document)
43+
cursor.setCharFormat(QTextCharFormat())
44+
cursor.clearSelection()
45+
self.textEdit.setTextCursor(cursor)
46+
47+
# 文字颜色
4348
fmt = QTextCharFormat()
4449
fmt.setForeground(col)
45-
# 先把光标移动到开头
50+
51+
# 正则
52+
expression = QRegExp(text)
4653
self.textEdit.moveCursor(QTextCursor.Start)
47-
while self.textEdit.find(text, QTextDocument.FindWholeWords): # 查找所有文字
48-
self.mergeFormatOnWordOrSelection(fmt)
54+
cursor = self.textEdit.textCursor()
55+
56+
# 循环查找设置颜色
57+
pos = 0
58+
index = expression.indexIn(self.textEdit.toPlainText(), pos)
59+
while index >= 0:
60+
cursor.setPosition(index)
61+
cursor.movePosition(QTextCursor.Right,
62+
QTextCursor.KeepAnchor, len(text))
63+
cursor.mergeCharFormat(fmt)
64+
pos = index + expression.matchedLength()
65+
index = expression.indexIn(self.textEdit.toPlainText(), pos)
4966

5067

5168
if __name__ == '__main__':

0 commit comments

Comments
 (0)