Pyqt5 输入 dict\list\str 生成treeWidget

在网上看了很多代码,感觉算法都不够优雅,封装得不够完美。
于是我自己就写了一个。

def generateTreeWidget(self, dictData):

        # 传入dictData参数,就是要生成tree的数据

        tree = QTreeWidget()  # 创建tree组件
        tree.setColumnCount(2)  # 有两列,分别显示key,value
        tree.setHeaderLabels(['key', 'value'])  # 设置两列的列名
        root = QTreeWidgetItem(tree)  # 创建tree组件的根
        root.setText(0, 'root')  # 根的key叫做‘root’,叫做其他的也可以,根没有value,就不设置

        # 通过dfs深度优先搜索来遍历整个dictData,有点抽象,下面我也不懂怎么注释
        # 但整个过程就像一棵树先长出树干、再长出树枝、再长出叶子
 
        def dfs(father, child):
            if type(child) is dict:
                for key in child:
                    childWidget = QTreeWidgetItem()
                    childWidget.setText(0, key)
                    father.addChild(childWidget)
                    dfs(childWidget, child[key])
                pass
            elif type(child) is list:
                for i in range(0, len(child)):
                    childWidget = QTreeWidgetItem()
                    childWidget.setText(0, str(i))
                    father.addChild(childWidget)
                    dfs(childWidget, child[i])
            else:
                father.setText(1, str(child))
                pass

        # 运行dfs函数来让树生长
        dfs(root, dictData)

        # 收尾工作
        widget = QWidget()
        mainBox = QVBoxLayout()
        mainBox.addWidget(tree)
        widget.setLayout(mainBox)

        # 优雅的返回一个QWidget对象
        return widget

猜你喜欢

转载自blog.csdn.net/weixin_45518621/article/details/129686853