pyside6 如何修改plaintextedit内的字体颜色
时间: 2025-01-27 13:07:35 浏览: 49
在 PySide6 中,可以通过 `QTextCharFormat` 和 `QTextCursor` 来修改 `QPlainTextEdit` 内的字体颜色。以下是一个示例代码,展示了如何实现这一功能:
```python
from PySide6.QtWidgets import QApplication, QMainWindow, QPlainTextEdit, QPushButton
from PySide6.QtGui import QTextCharFormat, QTextCursor, QColor
from PySide6.QtCore import Qt
import sys
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.plainTextEdit = QPlainTextEdit(self)
self.setCentralWidget(self.plainTextEdit)
self.button = QPushButton("Change Color", self)
self.button.clicked.connect(self.change_color)
self.button.move(0, self.plainTextEdit.height())
self.setGeometry(100, 100, 600, 400)
self.setWindowTitle("QPlainTextEdit Color Example")
def change_color(self):
# 获取当前光标位置
cursor = self.plainTextEdit.textCursor()
# 创建文本格式对象
format = QTextCharFormat()
format.setForeground(QColor("red"))
# 设置光标选择的文本格式
cursor.setCharFormat(format)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
```
在这个示例中,我们创建了一个 `QPlainTextEdit` 和一个按钮。当按钮被点击时,会调用 `change_color` 方法,该方法会修改当前选中文本的颜色为红色。
阅读全文
相关推荐


















