PyQt/QTextEdit/HighlightText.py

77 lines
2.3 KiB
Python
Raw Normal View History

2018-09-05 15:02:18 +08:00
import sys
2020-05-28 15:26:28 +08:00
from PyQt5.QtCore import QRegExp
2018-12-26 23:04:56 +08:00
from PyQt5.QtGui import QTextCharFormat, QTextDocument, QTextCursor
2018-09-05 15:02:18 +08:00
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit,
2018-12-26 23:04:56 +08:00
QToolBar, QLineEdit, QPushButton, QColorDialog, QHBoxLayout, QWidget)
2018-09-05 15:02:18 +08:00
class TextEdit(QMainWindow):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.textEdit = QTextEdit(self)
self.setCentralWidget(self.textEdit)
2018-12-26 23:04:56 +08:00
2018-09-05 15:02:18 +08:00
widget = QWidget(self)
vb = QHBoxLayout(widget)
vb.setContentsMargins(0, 0, 0, 0)
self.findText = QLineEdit(self)
self.findText.setText('self')
2018-12-26 23:04:56 +08:00
findBtn = QPushButton('高亮', self)
2018-09-05 15:02:18 +08:00
findBtn.clicked.connect(self.highlight)
vb.addWidget(self.findText)
vb.addWidget(findBtn)
2018-12-26 23:04:56 +08:00
2018-09-05 15:02:18 +08:00
tb = QToolBar(self)
tb.addWidget(widget)
2020-05-28 15:26:28 +08:00
self.addToolBar(tb)
2018-12-26 23:04:56 +08:00
def setText(self, text):
2018-09-05 15:02:18 +08:00
self.textEdit.setPlainText(text)
2018-12-26 23:04:56 +08:00
2018-09-05 15:02:18 +08:00
def highlight(self):
2018-12-26 23:04:56 +08:00
text = self.findText.text() # 输入框中的文字
2018-09-05 15:02:18 +08:00
if not text:
return
2020-05-28 15:26:28 +08:00
2018-09-05 15:02:18 +08:00
col = QColorDialog.getColor(self.textEdit.textColor(), self)
if not col.isValid():
return
2020-05-28 15:26:28 +08:00
# 恢复默认的颜色
cursor = self.textEdit.textCursor()
cursor.select(QTextCursor.Document)
cursor.setCharFormat(QTextCharFormat())
cursor.clearSelection()
self.textEdit.setTextCursor(cursor)
# 文字颜色
2018-09-05 15:02:18 +08:00
fmt = QTextCharFormat()
fmt.setForeground(col)
2020-05-28 15:26:28 +08:00
# 正则
expression = QRegExp(text)
2018-09-05 15:02:18 +08:00
self.textEdit.moveCursor(QTextCursor.Start)
2020-05-28 15:26:28 +08:00
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)
2018-09-05 15:02:18 +08:00
2018-12-26 23:04:56 +08:00
2018-09-05 15:02:18 +08:00
if __name__ == '__main__':
app = QApplication(sys.argv)
textEdit = TextEdit()
textEdit.resize(800, 600)
textEdit.show()
2018-12-26 23:04:56 +08:00
textEdit.setText(open(sys.argv[0], 'rb').read().decode())
2018-09-05 15:02:18 +08:00
2018-12-26 23:04:56 +08:00
sys.exit(app.exec_())