pyqt5 中 在textEdit已输入的内容 选出指定内容标红
时间: 2024-02-12 21:02:55 浏览: 24
您可以使用QTextEdit的`QTextEdit.find()`方法来查找并标记指定的文本。以下是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QTextEdit
from PyQt5.QtGui import QTextCursor, QTextCharFormat, QBrush, QColor
def highlight_text(text_edit, search_text):
# 清除之前的高亮
text_edit.moveCursor(QTextCursor.Start)
format = QTextCharFormat()
format.setBackground(QBrush(QColor("white")))
cursor = text_edit.textCursor()
cursor.select(QTextCursor.Document)
cursor.setCharFormat(format)
# 查找和高亮指定文本
cursor = text_edit.document().find(search_text)
while cursor:
format = QTextCharFormat()
format.setBackground(QBrush(QColor("yellow")))
cursor.mergeCharFormat(format)
cursor = text_edit.document().find(search_text, cursor)
if __name__ == '__main__':
app = QApplication([])
text_edit = QTextEdit()
text_edit.show()
text_edit.setText("Hello world!\nThis is a test.")
# 将 "world" 标记为红色
highlight_text(text_edit, "world")
app.exec_()
```
在上面的代码中,`highlight_text()`函数接收一个QTextEdit和要查找的文本作为参数。它首先清除之前的高亮,然后使用`QTextEdit.document().find()`方法查找文本,并使用`QTextCursor.mergeCharFormat()`方法将其标记为黄色。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)