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

PyQt5如何设置绑定QTableView的QStandardItemModel列宽并支持拖拽调整

实现方案

QTableView 的列宽调整能力由水平表头(QHeaderView)的 section 调整模式控制,要同时支持手动设置初始宽度+用户拖拽调整,只需将对应列的调整模式设为 Interactive 即可(该模式为默认值,若之前被修改过需要主动指定)。

调整模式说明

  • QHeaderView.Interactive:允许用户拖拽调整列宽,也支持代码手动修改宽度,符合你的需求
  • QHeaderView.Stretch:列宽自动铺满表格剩余空间,禁止拖拽,也无法手动设置固定宽度
  • QHeaderView.Fixed:列宽固定,禁止用户拖拽,仅能通过代码修改
  • QHeaderView.ResizeToContents:列宽自动适配单元格内容,禁止用户拖拽

修改后的可运行代码

from PyQt5.QtWidgets import QStandardItemModel, QTableView, QHeaderView

reportContentsWidgetModel = QStandardItemModel(4, 4)

reportColumnNames = ["website", "https://neehack.com", "neehack.com", "pubs"]
reportContentsWidgetModel.setHorizontalHeaderLabels(reportColumnNames)
reportContentsWidget = QTableView()

# 核心配置:设置所有列的调整模式为Interactive,支持拖拽调整
reportContentsWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)

# 按需设置初始列宽,两种方式二选一即可
# 方式1:按列内容自适应设置初始宽度
reportContentsWidget.resizeColumnToContents(0)
# 方式2:手动指定某列的固定初始宽度,比如将第0列设为180px
# reportContentsWidget.setColumnWidth(0, 180)

# 也可单独给不同列设置不同模式,比如第1列设为自动拉伸,其余列允许拖拽
# reportContentsWidget.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)

reportContentsWidget.setModel(reportContentsWidgetModel)

常见不生效问题排查

  • 如果之前全局设置过 setSectionResizeMode(QHeaderView.Stretch) 或者 setSectionResizeMode(QHeaderView.Fixed),会导致拖拽失效,必须改回 Interactive 模式
  • 不要在设置完初始列宽之后再修改调整模式,否则会覆盖之前设置的宽度值
  • 如果需要保存用户调整后的列宽,可以监听 horizontalHeader().sectionResized 信号,记录对应列的宽度值,下次初始化时直接赋值即可恢复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 17:15:04