SoFunction
Updated on 2024-11-10

PyQt5 QTreeWidget Tree structure recursive traversal of all current nodes implementation

Common methods in the QTreeWidget class

methodologies descriptive
setColumnWidth(int column,int width) Sets the width of the specified column to the given value width
insertTopLevelItems() Inserting a list of items in the top-level index of a view
expandAll() Expand all tree nodes
invisibleRootItem() Returns the root option that is not visible in the tree control.
selectedItems() Returns a list of all selected non-hidden items

Common methods in QTreeWidgetItem class

methodologies descriptive
addChild() Append subitem to sublist
setText() Setting the displayed node text
Text() Returns the displayed node text
setCheckState(column,state) Sets the selected state of the specified column: (node selected), (node unselected)
setIcon(column,icon) Display icons in the specified columns

Prepare a small demo

Common small demos
Introduction: Tree nested structure demo for product categories and products
Function:Click the button to get all the current selected products (with a little bit of private goods〃'▽'〃)
Note: limited space, did not write the child node and the parent node linkage selected, so in the selection of the child node trouble to select the parent node on their own, otherwise it will be skipped.

在这里插入图片描述

在这里插入图片描述

Code Blocker:

import sys
from  import QTreeWidgetItem, QTreeWidget, QWidget, QVBoxLayout, QPushButton, QApplication
from  import Qt


class Demo(QWidget):
    def __init__(self):
        super().__init__()
        # Instantiate a tree structure that hides the header
         = QTreeWidget()
        (True)
        # Top level branches
        self.tree_main = QTreeWidgetItem()
        self.tree_main.setText(0, 'Type of goods')
        # Set up some secondary branches
        tree_second = ['Electronics', 'Fruit', 'Daily necessities', 'Favorite people']
        self.gen_branch(self.tree_main, tree_second)
        # Setting up some tertiary branches
        tree_fruit = ['Apple', 'Banana', 'Pear']
        tree_daily_use = ['Tissue paper', 'Towel']
        tree_lovers = ['Didi 1', 'Didi 2']
        # child(1) means the first node of the branch, numbered from 0.
        self.gen_branch(self.tree_main.child(1), tree_fruit)
        self.gen_branch(self.tree_main.child(2), tree_daily_use)
        self.gen_branch(self.tree_main.child(3), tree_lovers)
        # A button
         = QPushButton('Chosen.')
        # Show it
         = QVBoxLayout()
        ()
        ()
        ()

        # Bind the slot function a bit, pass in the main branch node
        (lambda: self.get_checked(self.tree_main))

    @staticmethod
    def gen_branch(node: QTreeWidgetItem, texts: list):
        """ Given a node and a list, generate an in-list branch at that node."""
        for text in texts:
            item = QTreeWidgetItem()
            (0, text)
            (0, )
            (item)

    def get_checked(self, node: QTreeWidgetItem)->list:
        """ get all branches selected by the current node, return a list """
        temp_list = []
        # See note 1 below here
        for item in ():
            # Determine if it's selected
            if (0) == :
                temp_list.append((0))
                # Determine if there are sub-branches
                if ():
                    temp_list.extend(self.get_checked(item))
            (item)
        print(temp_list)
        return temp_list


if __name__ == '__main__':
    app = QApplication()
    win = Demo()
    ()
    (app.exec_())

Note 01: In this function, I pass in a node node, the method takeChildren() will take out (remove) all the first level child branches of that node node and return a list of all the first level branches of the node as shown below. This method can only return first-level node information, using childCount() to determine if there are any child branches, and recursively if there are, all the way down to the bottom node. Because takeChildren() removes all nodes during fetch, it rejoins the node at the end of the operation.

[
< object at 0x0000000008464708>, 
< object at 0x0000000008464798>, 
]

What are the advantages and disadvantages of such an approach?

The biggest benefit is definitely that there is no need to create additional variables to store information about the child nodes, and the information and order of the child nodes is obtained in real time rather than being predetermined up front. On the downside, I envision that if this method is used too often, the order of the nodes may change. For example, "apple, banana" becomes "banana, apple".

Compare methods on the web

There is an approach to QTreeWidgetItemIterator, which is a traverser that comes with Qt, roughly as follows

item = (),

Using () to locate a node, an instance of () is the kind of object in the list above, and personally I don't feel it's too far off.

There is also a more violent approach. When generating child nodes put all of them into the scope of the current class, i.e., they exist as attributes.

self.item1 = QTreeWidgetItem()

Or generated in a list defined in the scope, which has the disadvantage that the information about the nodes is fixed in advance. But in practice the situation encountered should be more unknown.

self.item_list = []
self.item_list.append([... ... ]) 

This article on PyQt5 QTreeWidget tree structure recursive traversal of the current implementation of all the nodes to this article, more related PyQt5 QTreeWidget tree structure traversal content, please search for my previous posts or continue to browse the following related articles I hope that you will support me in the future !