You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt6 QTableWidget文本颜色修改失效问题求助

QTableWidgetItem字体颜色设置不生效的解决方案

你的代码逻辑本身无错误,但在PyQt6中直接传入QColor给setForeground可能因类型隐式转换的兼容性问题导致样式不生效。解决方法是显式使用QBrush包裹QColor:

修改核心代码

将原代码中的:

item.setForeground(QColor('red'))

替换为:

from PyQt6.QtGui import QBrush
# ...
item.setForeground(QBrush(QColor('red')))

原因说明

QTableWidgetItem.setForeground()方法的参数类型为QBrush,虽然PyQt支持QColor到QBrush的隐式转换,但在部分环境或版本中存在转换失效的情况,显式创建QBrush可以确保字体颜色样式被正确应用。

如果你的复杂程序中使用了全局样式表,还需要检查是否有样式规则强制覆盖了表格项的字体颜色,比如类似以下的样式会导致自定义颜色失效:

QTableWidget::item {
    color: black;
}

完整可运行代码

import sys
from PyQt6.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QMainWindow
from PyQt6.QtGui import QColor, QBrush

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # Set up the table widget
        self.table = QTableWidget(1, 1)
        self.table.setHorizontalHeaderLabels(["Character"])

        # Create the table item with the "A" character
        item = QTableWidgetItem("A")

        # Set the font color of the item to red using QBrush
        item.setForeground(QBrush(QColor('red')))

        # Add the item to the table
        self.table.setItem(0, 0, item)

        # Set the table as the central widget of the window
        self.setCentralWidget(self.table)

        # Set the window title
        self.setWindowTitle("Table")

        # Set the window size
        self.resize(300, 200)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

内容的提问来源于stack exchange,提问作者Menachem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:17:17