from PyQt5.QtWidgets import QApplication, QTreeView, QMainWindow, QVBoxLayout, QWidget, QAbstractItemView
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import Qt

class SummaryTreeView(QTreeView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAnimated(True)
        self.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.collapsed.connect(self.show_summary)
        self.expanded.connect(self.hide_summary)
        self.summary_items = {}

    def show_summary(self, index):
        model = self.model()
        parent_item = model.itemFromIndex(index)
        if parent_item is None or parent_item.rowCount() == 0:
            return
        # Create summary text
        child_count = parent_item.rowCount()
        summary_text = f"[{child_count} items folded]"
        summary_item = QStandardItem(summary_text)
        summary_item.setFlags(summary_item.flags()|Qt.ItemIsEditable)
        # Insert summary as the last child
        model.setItem(index.row(), index.column(), summary_item)

    def hide_summary(self, index):
        model = self.model()
        parent_item = model.itemFromIndex(index)
        if index in self.summary_items:
            summary_item = self.summary_items.pop(index)
            parent_item.removeRow(summary_item.row())

def create_sample_model():
    model = QStandardItemModel()
    model.setHorizontalHeaderLabels(['Tree Data'])
    root = model.invisibleRootItem()

    for i in range(3):
        parent = QStandardItem(f'Parent {i}')
        for j in range(5):
            child = QStandardItem(f'Child {i}-{j}')
            parent.appendRow(child)
        root.appendRow(parent)
    return model

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Tree Data with Summary on Fold")
        self.resize(400, 300)
        layout = QVBoxLayout()
        self.tree = SummaryTreeView()
        self.tree.setModel(create_sample_model())
        layout.addWidget(self.tree)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())