#!/usr/bin/env python3 """ 测试字体颜色功能的简单脚本 """ import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) from PyQt5.QtWidgets import QApplication, QTextEdit, QPushButton, QVBoxLayout, QWidget, QColorDialog from PyQt5.QtGui import QColor, QTextCharFormat, QTextCursor from PyQt5.QtCore import Qt def test_color_function(): """测试字体颜色功能""" app = QApplication(sys.argv) # 创建主窗口 window = QWidget() window.setWindowTitle("字体颜色测试") window.setGeometry(100, 100, 400, 300) # 创建文本编辑器 text_edit = QTextEdit() text_edit.setPlainText("这是一段测试文本。请选择这段文字并点击颜色按钮来更改颜色。") # 创建颜色按钮 color_btn = QPushButton("选择颜色") def change_color(): """更改字体颜色""" color = QColorDialog.getColor(Qt.black, window, "选择字体颜色") if color.isValid(): cursor = text_edit.textCursor() if cursor.hasSelection(): # 如果有选中文本,只更改选中文本的颜色 fmt = cursor.charFormat() fmt.setForeground(color) cursor.setCharFormat(fmt) print(f"已更改选中文本颜色为: {color.name()}") else: # 如果没有选中文本,更改整个文档的默认颜色 text_edit.setTextColor(color) print(f"已更改默认文本颜色为: {color.name()}") color_btn.clicked.connect(change_color) # 布局 layout = QVBoxLayout() layout.addWidget(text_edit) layout.addWidget(color_btn) window.setLayout(layout) window.show() print("字体颜色测试窗口已打开") print("操作说明:") print("1. 在文本编辑器中选择一些文字") print("2. 点击'选择颜色'按钮") print("3. 选择颜色并确认") print("4. 观察选中文本的颜色是否改变") sys.exit(app.exec_()) if __name__ == "__main__": test_color_function()