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

如何设置QTreeWidget中编辑器宽度以填充单元格?

QTreeWidget 单元格编辑器填充整个单元格的解决方案

默认情况下,QTreeWidget的单元格编辑器宽度会跟随输入文本的长度变化,想要让编辑器完全填充所在的单元格,我们可以通过**自定义项委托(ItemDelegate)**或者直接重写QTreeWidget的createEditor方法来实现,下面是具体的实现方案:

方法一:直接重写QTreeWidget的createEditor方法

这种方式适合只需要在当前TreeWidget中生效的场景,直接在你的Example类中添加createEditor方法即可:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class Example(QTreeWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 400)
        self.setHeaderLabels(['Col1', 'Col2', 'Col3', 'Col4'])
        self.setRootIsDecorated(False)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.setStyleSheet('QTreeView { show-decoration-selected: 1;}')
        for i in range(5):
            item = QTreeWidgetItem(['hello', 'bello'])
            item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.addTopLevelItem(item)

    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget:
        # 调用父类方法创建默认编辑器(通常是QLineEdit)
        editor = super().createEditor(parent, option, index)
        # 设置编辑器水平方向填充可用空间
        editor.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        # 强制编辑器宽度匹配单元格的实际宽度
        editor.setFixedWidth(option.rect.width())
        return editor

def main():
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

方法二:自定义ItemDelegate(适合多视图复用)

如果需要在多个QTreeWidget甚至其他视图组件中统一应用这个效果,自定义委托会更灵活:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class FullWidthDelegate(QStyledItemDelegate):
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget:
        editor = super().createEditor(parent, option, index)
        editor.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        editor.setFixedWidth(option.rect.width())
        return editor

class Example(QTreeWidget):
    def __init__(self):
        super().__init__()
        self.resize(600, 400)
        self.setHeaderLabels(['Col1', 'Col2', 'Col3', 'Col4'])
        self.setRootIsDecorated(False)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.setStyleSheet('QTreeView { show-decoration-selected: 1;}')
        # 给TreeWidget设置自定义委托
        self.setItemDelegate(FullWidthDelegate(self))
        for i in range(5):
            item = QTreeWidgetItem(['hello', 'bello'])
            item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.addTopLevelItem(item)

def main():
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

原理说明

  • 通过重写createEditor方法,我们可以获取到当前单元格的矩形区域参数(option.rect),从而精准设置编辑器的宽度与单元格一致。
  • QSizePolicy.Expanding确保编辑器在布局中会尽可能填充可用空间,配合setFixedWidth可以让编辑器完美适配单元格宽度。

修改完成后,双击单元格进入编辑状态时,编辑器就会完全填充整个单元格的宽度了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:55:52