简体   繁体   English

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

[英]Set editor width in QTreeWidget to fill cell

By default if a cell is edited in a QTreeWidget, the editor changes its width based on length of text.默认情况下,如果在 QTreeWidget 中编辑单元格,编辑器会根据文本长度更改其宽度。 在此处输入图像描述

Is it possible to set the editor´s width to fill the cell?是否可以设置编辑器的宽度以填充单元格?

Here is the code to reproduce the screenshot:这是重现屏幕截图的代码:

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()

You can create a simple QStyledItemDelegate and override its updateEditorGeometry() in order to always resize it to the index rectangle:您可以创建一个简单的 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))

** UPDATE ** ** 更新 **

The default text editor for all item views is an auto expanding QLineEdit, which tries to expand itself to the maximum available width (the right edge of the viewport) if the text is longer than the visual rectangle of the item.所有项目视图的默认文本编辑器是一个自动扩展的 QLineEdit,如果文本比项目的可视矩形长,它会尝试将自身扩展到最大可用宽度(视口的右边缘)。 In order to avoid this behavior and always use the item rect, you have to return a standard QLineEdit.为了避免这种行为并始终使用项目 rect,您必须返回标准 QLineEdit。 In this case the updateGeometry override is usually not necessary anymore (but I'd keep it anyway, as some styles might still prevent that):在这种情况下,通常不再需要updateGeometry覆盖(但我还是会保留它,因为某些 styles 可能仍会阻止):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM