1
1
import sys
2
+ from PyQt5 .QtCore import QRegExp
2
3
from PyQt5 .QtGui import QTextCharFormat , QTextDocument , QTextCursor
3
4
from PyQt5 .QtWidgets import (QApplication , QMainWindow , QTextEdit ,
4
5
QToolBar , QLineEdit , QPushButton , QColorDialog , QHBoxLayout , QWidget )
@@ -22,30 +23,46 @@ def __init__(self, parent=None):
22
23
23
24
tb = QToolBar (self )
24
25
tb .addWidget (widget )
26
+ self .addToolBar (tb )
25
27
26
28
def setText (self , text ):
27
29
self .textEdit .setPlainText (text )
28
30
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
-
36
31
def highlight (self ):
37
32
text = self .findText .text () # 输入框中的文字
38
33
if not text :
39
34
return
35
+
40
36
col = QColorDialog .getColor (self .textEdit .textColor (), self )
41
37
if not col .isValid ():
42
38
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
+ # 文字颜色
43
48
fmt = QTextCharFormat ()
44
49
fmt .setForeground (col )
45
- # 先把光标移动到开头
50
+
51
+ # 正则
52
+ expression = QRegExp (text )
46
53
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 )
49
66
50
67
51
68
if __name__ == '__main__' :
0 commit comments