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

Windows11下QTableWidget单元格背景色存在圆角留白问题

解决Windows 11下QTableWidgetItem背景色无法填满单元格的问题

Windows 11系统中,使用item.setBackground(QColor(...))给QTableWidget项设置背景色时,默认样式会自带圆角留白,导致颜色无法填满整个单元格。以下是两种可行的解决方法:

方法一:通过QSS重置单元格样式

直接用QSS清除QTableWidget项的内边距和边框,让setBackground设置的颜色能完全覆盖单元格,同时不影响指定行/项单独设置背景色的需求。

修改后的代码示例:

from PySide6.QtWidgets import QMainWindow, QApplication, QTableWidget, QTableWidgetItem, QVBoxLayout
from PySide6.QtGui import QColor

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

        layout = QVBoxLayout()

        table = QTableWidget()
        table.setRowCount(2)
        table.setColumnCount(1)
        
        # 添加QSS重置单元格样式
        table.setStyleSheet("""
            QTableWidget::item {
                padding: 0px;
                border: none;
            }
        """)

        # 第一行设置红色背景
        item1 = QTableWidgetItem("测试行1")
        table.setItem(0, 0, item1)
        item1.setBackground(QColor(255, 0, 0))
        
        # 第二行保持默认
        item2 = QTableWidgetItem("测试行2")
        table.setItem(1, 0, item2)

        self.setCentralWidget(table)
        layout.addWidget(table)
        self.setLayout(layout)
        
            
if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

方法二:自定义ItemDelegate绘制背景

通过重写QStyledItemDelegate的paint方法,手动绘制单元格背景,完全规避默认样式的限制。

代码示例:

from PySide6.QtWidgets import QMainWindow, QApplication, QTableWidget, QTableWidgetItem, QVBoxLayout, QStyledItemDelegate
from PySide6.QtGui import QColor, Qt

class NoPaddingDelegate(QStyledItemDelegate):
    def paint(self, painter, option, index):
        # 优先绘制自定义背景色
        bg_color = index.data(Qt.BackgroundRole)
        if bg_color.isValid():
            painter.fillRect(option.rect, bg_color)
        # 调用父类方法绘制文本等其他内容
        super().paint(painter, option, index)

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

        layout = QVBoxLayout()

        table = QTableWidget()
        table.setRowCount(2)
        table.setColumnCount(1)
        
        # 设置自定义Delegate
        table.setItemDelegate(NoPaddingDelegate())

        # 第一行设置红色背景
        item1 = QTableWidgetItem("测试行1")
        table.setItem(0, 0, item1)
        item1.setBackground(QColor(255, 0, 0))
        
        # 第二行保持默认
        item2 = QTableWidgetItem("测试行2")
        table.setItem(1, 0, item2)

        self.setCentralWidget(table)
        layout.addWidget(table)
        self.setLayout(layout)
        
            
if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec()

两种方法都能解决Windows 11下的圆角留白问题,且支持单独给指定行/项设置背景色。如果需要更复杂的样式控制,自定义Delegate的灵活性更高;若需求简单,QSS方法更快捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 00:58:12