|
发表于 2024-3-19 15:15:57
|
显示全部楼层
当然可以!你可以在QPlainTextEdit中定义颜色函数,并在打印输出时调用这些函数来设置各行的字体颜色。下面是一个示例代码:- from PySide6.QtCore import Qt
- from PySide6.QtGui import QTextCharFormat
- from PySide6.QtWidgets import QApplication, QPlainTextEdit
- class MyPlainTextEdit(QPlainTextEdit):
- def __init__(self):
- super().__init__()
- self.color_functions = [self.set_red_color, self.set_white_color, self.set_yellow_color]
- def set_red_color(self, text):
- cursor = self.textCursor()
- format = QTextCharFormat()
- format.setForeground(Qt.red)
- cursor.insertText(text, format)
- def set_white_color(self, text):
- cursor = self.textCursor()
- format = QTextCharFormat()
- format.setForeground(Qt.white)
- cursor.insertText(text, format)
- def set_yellow_color(self, text):
- cursor = self.textCursor()
- format = QTextCharFormat()
- format.setForeground(Qt.yellow)
- cursor.insertText(text, format)
- def print_with_color(self, text, color_index):
- if color_index < 0 or color_index >= len(self.color_functions):
- color_index = 0
- self.color_functions[color_index](text)
- # 创建应用程序和主窗口
- app = QApplication([])
- window = MyPlainTextEdit()
- window.show()
- # 测试打印输出
- window.print_with_color("This line is in red color.\n", 0)
- window.print_with_color("This line is in white color.\n", 1)
- window.print_with_color("This line is in yellow color.\n", 2)
- app.exec()
复制代码
在这个示例代码中,我们创建了一个自定义的MyPlainTextEdit类,继承自QPlainTextEdit。在MyPlainTextEdit中,我们定义了三个颜色函数:set_red_color、set_white_color和set_yellow_color,分别用来设置红色、白色和黄色的字体颜色。然后,我们还定义了一个print_with_color方法,在该方法中根据color_index参数调用相应的颜色函数来设置打印输出的字体颜色。最后,我们创建了应用程序并在MyPlainTextEdit对象中进行测试打印输出。
希望这个例子对你有所帮助!如果有任何问题,请随时问我。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|