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

如何将PySide6 QTableWidget的指定列宽度设置为15pt?

问题解决方法

两个问题的核心原因如下:

  1. QTableWidget的水平表头默认有minimumSectionSize限制,默认值约为20,所以列宽无法缩小到该值以下
  2. 未给对应列设置固定宽度和固定缩放模式,启动时会按默认规则自动分配列宽

修复步骤

  • 导入QHeaderView组件
  • 初始化表格后添加3行配置代码,放开表头最小尺寸限制、给目标列设置固定宽度、固定列缩放模式

完整可运行代码

import sys
from PySide6.QtWidgets import (
    QMainWindow, QApplication, QTableWidget, QLabel, QPushButton, QHeaderView
)
from PySide6.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("My App")

        Nrows, Ncols = 5, 3
        table = QTableWidget(Nrows, Ncols, self)

        # 修复代码
        table.horizontalHeader().setMinimumSectionSize(0) # 取消表头列最小尺寸限制
        table.setColumnWidth(1, 15) # 设置第2列初始宽度为15
        table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Fixed) # 固定该列宽度避免自动拉伸

        for col in [0, 2]:
            for row in range(Nrows):
                table.setCellWidget(row, col,
                    QLabel(f"row {row} column {col}")
                )
        for row in range(Nrows):
            push = QPushButton("T")
            push.setFixedWidth(15)
            table.setCellWidget(row, 1,push)

        self.setCentralWidget(table)

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()

修改后启动程序即可看到第2列默认就是15pt宽度,也支持手动调整到更小尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:42:02