PyQt5 QTextEdit设置单词里面某个字母的颜色
时间: 2024-10-18 19:17:13 浏览: 21
在PyQt5中,你可以使用`QTextEdit`和`QSyntaxHighlighter`来设置文本块内的特定单词颜色。`QSyntaxHighlighter`允许你自定义文本高亮规则,包括颜色、字体等。
首先,你需要创建一个`QSyntaxHighlighter`的子类,并实现`highlightBlock()`方法,这个方法会在处理每一行文本时被调用。在这个方法里,你可以检查每个单词是否匹配你要高亮的关键字,并应用相应的样式。
下面是一个简单的例子,展示如何设置"Python"这个词为红色:
```python
from PyQt5.QtGui import QTextCharFormat, QColor
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QTextEdit, QVBoxLayout
class Highlighter(QSyntaxHighlighter):
def __init__(self, parent=None):
super().__init__(parent)
self.highlightingRules = []
keyword_format = QTextCharFormat()
keyword_format.setForeground(QColor('red')) # 设置颜色为红色
keyword_format.setFontWeight(Qt.Bold) # 加粗显示
pattern = r'\bPython\b' # 匹配单词"Python"
rule = (pattern, keyword_format)
self.highlightingRules.append(rule)
def highlightBlock(self, text):
for pattern, format in self.highlightingRules:
expression = QRegExp(pattern)
index = expression.indexIn(text)
while index >= 0:
length = expression.matchedLength()
self.setFormat(index, length, format)
index = expression.indexIn(text, index + length)
app = QApplication([])
text_edit = QTextEdit()
layout = QVBoxLayout()
layout.addWidget(text_edit)
highlighter = Highlighter(text_edit.document())
text_edit.setDocument(highlighter.document())
# 示例文字
text = "This is a sample text using Python for highlighting."
text_edit.setPlainText(text)
text_edit.show()
app.exec_()
```
阅读全文