forked from PyQt5/PyQt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HighlightText.py
59 lines (48 loc) · 1.92 KB
/
HighlightText.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import sys
from PyQt5.QtGui import QTextCharFormat, QTextDocument, QTextCursor
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit,
QToolBar, QLineEdit, QPushButton, QColorDialog, QHBoxLayout, QWidget)
class TextEdit(QMainWindow):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.textEdit = QTextEdit(self)
self.setCentralWidget(self.textEdit)
widget = QWidget(self)
vb = QHBoxLayout(widget)
vb.setContentsMargins(0, 0, 0, 0)
self.findText = QLineEdit(self)
self.findText.setText('self')
findBtn = QPushButton('高亮', self)
findBtn.clicked.connect(self.highlight)
vb.addWidget(self.findText)
vb.addWidget(findBtn)
tb = QToolBar(self)
tb.addWidget(widget)
def setText(self, text):
self.textEdit.setPlainText(text)
def mergeFormatOnWordOrSelection(self, format):
cursor = self.textEdit.textCursor()
if not cursor.hasSelection():
cursor.select(QTextCursor.WordUnderCursor)
cursor.mergeCharFormat(format)
self.textEdit.mergeCurrentCharFormat(format)
def highlight(self):
text = self.findText.text() # 输入框中的文字
if not text:
return
col = QColorDialog.getColor(self.textEdit.textColor(), self)
if not col.isValid():
return
fmt = QTextCharFormat()
fmt.setForeground(col)
# 先把光标移动到开头
self.textEdit.moveCursor(QTextCursor.Start)
while self.textEdit.find(text, QTextDocument.FindWholeWords): # 查找所有文字
self.mergeFormatOnWordOrSelection(fmt)
if __name__ == '__main__':
app = QApplication(sys.argv)
textEdit = TextEdit()
textEdit.resize(800, 600)
textEdit.show()
textEdit.setText(open(sys.argv[0], 'rb').read().decode())
sys.exit(app.exec_())