forked from PyQt5/PyQt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HighlightText.py
95 lines (77 loc) · 2.84 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2019年5月22日
@author: Irony
@site: https://pyqt.site , https://github.com/PyQt5
@email: [email protected]
@file:
@description:
"""
import sys
try:
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QTextCharFormat, QTextCursor
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit,
QToolBar, QLineEdit, QPushButton, QColorDialog, QHBoxLayout, QWidget)
except ImportError:
from PySide2.QtCore import QRegExp
from PySide2.QtGui import QTextCharFormat, QTextCursor
from PySide2.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)
self.addToolBar(tb)
def setText(self, text):
self.textEdit.setPlainText(text)
def highlight(self):
text = self.findText.text() # 输入框中的文字
if not text:
return
col = QColorDialog.getColor(self.textEdit.textColor(), self)
if not col.isValid():
return
# 恢复默认的颜色
cursor = self.textEdit.textCursor()
cursor.select(QTextCursor.Document)
cursor.setCharFormat(QTextCharFormat())
cursor.clearSelection()
self.textEdit.setTextCursor(cursor)
# 文字颜色
fmt = QTextCharFormat()
fmt.setForeground(col)
# 正则
expression = QRegExp(text)
self.textEdit.moveCursor(QTextCursor.Start)
cursor = self.textEdit.textCursor()
# 循环查找设置颜色
pos = 0
index = expression.indexIn(self.textEdit.toPlainText(), pos)
while index >= 0:
cursor.setPosition(index)
cursor.movePosition(QTextCursor.Right,
QTextCursor.KeepAnchor, len(text))
cursor.mergeCharFormat(fmt)
pos = index + expression.matchedLength()
index = expression.indexIn(self.textEdit.toPlainText(), pos)
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_())