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

如何消除PySide6中QTableWidget底部的空白区域?

解决PySide6 QTableWidget底部空白问题

你的问题出在QAbstractScrollArea.AdjustToContents的自动大小调整不够精确,加上控件的边框、内边距等额外元素未被正确计算。可以通过手动计算表格所需的精确高度消除底部空白,同时隐藏垂直滚动条避免占位。

修改后的完整代码

from PySide6.QtWidgets import *
from PySide6.QtCore import Qt


class MW(QWidget):
    def __init__(self):
        super().__init__()

        self.button = QPushButton("Test")

        self.table = QTableWidget(self)
        self.table.setColumnCount(1)
        # 关闭垂直滚动条,避免滚动条占位导致空白
        self.table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # 保留水平方向自适应,垂直方向手动控制
        self.table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContentsOnFirstShow)

        self.setLayout(QVBoxLayout(self))
        self.layout().addWidget(self.button)
        self.layout().addWidget(self.table)

        self.button.clicked.connect(self.test)

    def test(self):
        self.table.insertRow(0)
        self.table.setItem(0, 0, QTableWidgetItem("new item"))
        
        # 手动计算表格精确高度
        total_height = self.table.horizontalHeader().height()  # 表头高度
        # 累加所有行的高度
        for row in range(self.table.rowCount()):
            total_height += self.table.rowHeight(row)
        # 加上表格边框和内边距
        total_height += self.table.frameWidth() * 2
        total_height += self.table.contentsMargins().top() + self.table.contentsMargins().bottom()
        
        # 设置表格固定高度
        self.table.setFixedHeight(total_height)
        # 调整主窗口适配内容
        self.adjustSize()


app = QApplication()
mw = MW()
mw.show()
app.exec()

关键修改说明

  • 隐藏垂直滚动条:避免滚动条的默认占位空间导致底部出现空白区域。
  • 手动计算高度:直接累加表头高度、所有行的高度,再加上表格的边框和内边距,确保高度完全匹配内容。
  • 调整大小策略:将垂直方向的自动调整改为手动控制,只保留水平方向的自适应,避免冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:16:13