将行添加到父节点后,修改父节点以显示下面的子节点数

After adding row to a parent node, modify parent to show number of children below

我正在遍历我的数据,使用 addrow 到根节点或作为它的父节点(等等)。现在对于父级,如何修改父级中的第二个单元格以显示当前子级数,然后在我添加更多子级时更新该单元格?

一种可能的解决方案是使用来自模型的 rowsInserted and rowsRemoved 信号来计算 children 的数量。另一方面,更简单的解决方案是使用委托:

import random

from PyQt5 import QtCore, QtGui, QtWidgets


class Delegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if not index.parent().isValid() and index.column() == 1:
            model = index.model()
            sibling = index.sibling(index.row(), 0)
            option.text = f"{model.rowCount(sibling)} childs"


def main():
    app = QtWidgets.QApplication([])

    model = QtGui.QStandardItemModel(0, 2)

    for i in range(4):
        item = QtGui.QStandardItem(f"parent-{i}")
        model.appendRow(item)

    view = QtWidgets.QTreeView()
    delegate = Delegate(view)
    view.setItemDelegate(delegate)
    view.setModel(model)
    view.resize(640, 480)
    view.show()

    def handle_timeout():
        for i in range(4):
            root_item = model.item(i)
            for j in range(random.randint(3, 5)):
                item = QtGui.QStandardItem(f"child-{i}-{j}")
                root_item.appendRow(item)
        view.expandAll()

    QtCore.QTimer.singleShot(2 * 1000, handle_timeout)

    app.exec_()


if __name__ == "__main__":
    main()