在 QTreeWidget 中设置编辑器宽度以填充单元格

问题描述

认情况下,如果在 QTreeWidget 中编辑单元格,编辑器会根据文本长度更改其宽度。

enter image description here

是否可以设置编辑器的宽度来填充单元格?

这是重现屏幕截图的代码

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.setSelectionMode(QAbstractItemView.SingleSelection)
        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 main():

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


if __name__ == '__main__':
    main()

解决方法

您可以创建一个简单的 QStyledItemDelegate 并覆盖其 updateEditorGeometry() 以始终将其调整为索引矩形:

class FullSizedDelegate(QStyledItemDelegate):
    def updateEditorGeometry(self,editor,opt,index):
        editor.setGeometry(opt.rect)


class Example(QTreeWidget):
    def __init__(self):
        # ...
        self.setItemDelegate(FullSizedDelegate(self))

** 更新 **

所有项目视图的默认文本编辑器是自动扩展的 QLineEdit,如果文本长于项目的可视矩形,它会尝试将自身扩展到最大可用宽度(视口的右边缘)。为了避免这种行为并始终使用项目 rect,您必须返回一个标准的 QLineEdit。在这种情况下,通常不再需要 updateGeometry 覆盖(但我还是会保留它,因为某些样式可能仍会阻止这种情况发生):

class FullSizedDelegate(QStyledItemDelegate):
    def createEditor(self,parent,index):
        if index.data() is None or isinstance(index.data(),str):
            return QLineEdit(parent)
        return super().createEditor(parent,index)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...