You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
3.3 KiB
78 lines
3.3 KiB
# 字体颜色功能测试脚本 - 验证保留之前内容的颜色
|
|
import sys
|
|
from PyQt5.QtWidgets import QApplication, QTextEdit, QPushButton, QVBoxLayout, QWidget, QColorDialog
|
|
from PyQt5.QtCore import Qt
|
|
from PyQt5.QtGui import QColor, QTextCharFormat, QFont
|
|
|
|
class ColorTestWindow(QWidget):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.setWindowTitle("字体颜色功能测试 - 保留之前内容的颜色")
|
|
self.setGeometry(100, 100, 600, 400)
|
|
|
|
layout = QVBoxLayout()
|
|
|
|
# 创建文本编辑器
|
|
self.text_edit = QTextEdit()
|
|
self.text_edit.setPlainText("这是一段测试文本。\n这行文字将保持原有颜色。\n新输入的文字将使用新颜色。")
|
|
|
|
# 设置一些初始颜色来模拟原有内容
|
|
cursor = self.text_edit.textCursor()
|
|
cursor.select(cursor.Document)
|
|
cursor.setPosition(0)
|
|
|
|
# 给第一行设置红色
|
|
cursor.movePosition(cursor.StartOfLine)
|
|
cursor.movePosition(cursor.EndOfLine, cursor.KeepAnchor)
|
|
fmt = QTextCharFormat()
|
|
fmt.setForeground(QColor("red"))
|
|
cursor.setCharFormat(fmt)
|
|
|
|
# 给第二行设置蓝色
|
|
cursor.movePosition(cursor.NextBlock)
|
|
cursor.movePosition(cursor.EndOfLine, cursor.KeepAnchor)
|
|
fmt.setForeground(QColor("blue"))
|
|
cursor.setCharFormat(fmt)
|
|
|
|
layout.addWidget(self.text_edit)
|
|
|
|
# 创建颜色选择按钮
|
|
self.color_btn = QPushButton("选择新颜色(保留原有内容颜色)")
|
|
self.color_btn.clicked.connect(self.on_color_clicked)
|
|
layout.addWidget(self.color_btn)
|
|
|
|
# 创建说明标签
|
|
self.info_label = QLabel("点击按钮选择颜色,新输入的文本将使用新颜色,原有内容颜色保持不变")
|
|
layout.addWidget(self.info_label)
|
|
|
|
self.setLayout(layout)
|
|
|
|
def on_color_clicked(self):
|
|
"""字体颜色按钮点击处理 - 保留之前内容的颜色"""
|
|
# 显示颜色选择对话框,默认使用当前文本颜色
|
|
current_color = self.text_edit.textColor()
|
|
color = QColorDialog.getColor(current_color, self, "选择字体颜色")
|
|
|
|
if color.isValid():
|
|
# 只设置后续输入的默认颜色,不影响已有内容
|
|
self.text_edit.setTextColor(color)
|
|
|
|
# 如果有选中文本,提示用户颜色只对新输入生效
|
|
cursor = self.text_edit.textCursor()
|
|
if cursor.hasSelection():
|
|
self.info_label.setText("字体颜色已设置,新输入的文本将使用该颜色(原有内容颜色保持不变)")
|
|
else:
|
|
self.info_label.setText(f"新颜色已设置: {color.name()},后续输入将使用该颜色")
|
|
|
|
if __name__ == "__main__":
|
|
app = QApplication(sys.argv)
|
|
window = ColorTestWindow()
|
|
window.show()
|
|
|
|
print("测试说明:")
|
|
print("1. 文本编辑器中有三行文字,第一行红色,第二行蓝色,第三行默认黑色")
|
|
print("2. 点击颜色选择按钮选择新颜色")
|
|
print("3. 在文本末尾输入新文字,观察新文字使用新颜色而原有文字颜色不变")
|
|
print("4. 测试验证:保留之前内容的颜色功能是否正常工作")
|
|
|
|
sys.exit(app.exec_()) |