【问题标题】:After adding row to a parent node, modify parent to show number of children below将行添加到父节点后,修改父节点以显示下面的子节点数
【发布时间】:2021-11-23 17:29:18
【问题描述】:

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

【问题讨论】:

    标签: python pyqt5 qtreeview qstandarditem


    【解决方案1】:

    一种可能的解决方案是使用模型中的rowsInsertedrowsRemoved 信号来计算孩子的数量。另一方面,更简单的解决方案是使用委托:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 2020-08-25
      • 1970-01-01
      相关资源
      最近更新 更多