MCPcopy Index your code
hub / github.com/PyQt5/PyQt / TextEdit

Class TextEdit

QTextEdit/HighlightText.py:27–84  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

25
26
27class TextEdit(QMainWindow):
28 def __init__(self, parent=None):
29 super(TextEdit, self).__init__(parent)
30 self.textEdit = QTextEdit(self)
31 self.setCentralWidget(self.textEdit)
32
33 widget = QWidget(self)
34 vb = QHBoxLayout(widget)
35 vb.setContentsMargins(0, 0, 0, 0)
36 self.findText = QLineEdit(self)
37 self.findText.setText('self')
38 findBtn = QPushButton('高亮', self)
39 findBtn.clicked.connect(self.highlight)
40 vb.addWidget(self.findText)
41 vb.addWidget(findBtn)
42
43 tb = QToolBar(self)
44 tb.addWidget(widget)
45 self.addToolBar(tb)
46
47 def setText(self, text):
48 self.textEdit.setPlainText(text)
49
50 def highlight(self):
51 text = self.findText.text() # 输入框中的文字
52 if not text:
53 return
54
55 col = QColorDialog.getColor(self.textEdit.textColor(), self)
56 if not col.isValid():
57 return
58
59 # 恢复默认的颜色
60 cursor = self.textEdit.textCursor()
61 cursor.select(QTextCursor.Document)
62 cursor.setCharFormat(QTextCharFormat())
63 cursor.clearSelection()
64 self.textEdit.setTextCursor(cursor)
65
66 # 文字颜色
67 fmt = QTextCharFormat()
68 fmt.setForeground(col)
69
70 # 正则
71 expression = QRegExp(text)
72 self.textEdit.moveCursor(QTextCursor.Start)
73 cursor = self.textEdit.textCursor()
74
75 # 循环查找设置颜色
76 pos = 0
77 index = expression.indexIn(self.textEdit.toPlainText(), pos)
78 while index >= 0:
79 cursor.setPosition(index)
80 cursor.movePosition(QTextCursor.Right,
81 QTextCursor.KeepAnchor, len(text))
82 cursor.mergeCharFormat(fmt)
83 pos = index + expression.matchedLength()
84 index = expression.indexIn(self.textEdit.toPlainText(), pos)

Callers 1

HighlightText.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected