pyside6 如何单独修改plaintextedit内指定字体的颜色,其余的文本不变
时间: 2025-01-27 20:16:12 浏览: 60
在PySide6中,你可以使用QTextCursor来操作QPlainTextEdit中的文本,并单独修改指定文本的颜色。以下是一个示例代码,展示了如何实现这一功能:
```python
from PySide6.QtWidgets import QApplication, QPlainTextEdit, QTextEdit, QPushButton, QVBoxLayout, QWidget
from PySide6.QtGui import QTextCursor, QTextCharFormat, QColor
from PySide6.QtCore import Qt
class TextEditor(QWidget):
def __init__(self):
super().__init__()
self.plain_text_edit = QPlainTextEdit()
self.plain_text_edit.setPlainText("This is a sample text. We will change the color of the word 'sample'.")
self.change_color_button = QPushButton("Change Color")
self.change_color_button.clicked.connect(self.change_color)
layout = QVBoxLayout()
layout.addWidget(self.plain_text_edit)
layout.addWidget(self.change_color_button)
self.setLayout(layout)
def change_color(self):
text_to_change = "sample"
text = self.plain_text_edit.toPlainText()
cursor = self.plain_text_edit.textCursor()
format = QTextCharFormat()
format.setForeground(QColor("red"))
index = text.find(text_to_change)
if index >= 0:
cursor.setPosition(index)
cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(text_to_change))
cursor.setCharFormat(format)
if __name__ == "__main__":
app = QApplication([])
editor = TextEditor()
editor.show()
app.exec()
```
在这个示例中,我们创建了一个QPlainTextEdit和一个QPushButton。当点击按钮时,`change_color`方法会被调用。该方法会查找文本中指定的部分(在这个例子中是"sample"),并将其颜色更改为红色。
阅读全文
相关推荐

















