Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

帮我用pyqt的mvd创建一个层级面板树,其中每个节点都有四列

  1. User

    帮我用pyqt的mvd创建一个层级面板树,其中每个节点都有四列

  2. Assistant

    下面是一个简单的例子来创建一个带有四列的层次树结构,使用QTreeView和QStandardItemModel。

    import sys
    from PyQt5.QtWidgets import QApplication, QWidget, QTreeView, QStandardItemModel, QStandardItem
    
    class MyTreeView(QTreeView):
        def __init__(self, data):
            super().__init__()
    
            # 创建标准模型
            model = QStandardItemModel()
            self.setModel(model)
    
            # 设置树的数据
            self.set_data(data)
    
        def set_data(self, data, parent=None):
            model = self.model()
            if parent is None:
                parent = model.invisibleRootItem()
    
            for item in data:
                # 创建一个标准项
                standard_item = QStandardItem()
                parent.appendRow(standard_item)
    
                # 设置标准项的数据
                standard_item.setData(item[0], Qt.DisplayRole)
                for i in range(1, len(item)):
                    standard_item.setData(item[i], Qt.UserRole+i)
    
                # 若该节点有子节点,则递归调用set_data()函数
                if len(item) > 1:
                    self.set_data(item[1], parent=standard_item)
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
    
        data = [
            ["Node1", "Info 1", "Category 1", "Type 1"],
            ["Node2", "Info 2", "Category 1", "Type 2"],
            ["Node3", [
                ["Node3-1", "Info 3-1", "Category 2", "Type 3-1"],
                ["Node3-2", "Info 3-2", "Category 2", "Type 3-2"]
            ], "Category 1", "Type 3"]
        ]
    
        tree = MyTreeView(data)
        tree.show()
    
        sys.exit(app.exec_())
    

    在这个例子中使用QStandardItemModel来作为TreeModel,QStandardItem作为TreeItem,其中每个节点都有四列,第一列为节点名称,后面三列为节点的其他信息。set_data递归遍历结构,每当创建一个新的节点时,通过setData方法来设置每列的数据。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.