SoFunction
Updated on 2025-04-27

Implementation of QTreeView class in PyQt6/PySide6

Implementation of QTreeView class in PyQt6/PySide6

Updated: April 27, 2025 11:14:37 Author: Randeng Studio
QTreeView is a control used to display hierarchical data in PyQt6 or PySide6 library. This article mainly introduces the implementation of the QTreeView class in PyQt6/PySide6. It has certain reference value. If you are interested, you can learn about it.

QTreeViewIt is a control used in the PyQt6 or PySide6 library to display hierarchical data. It is suitable for displaying tree structure data, such as file systems, organizational structures, etc.QTreeViewIt is also based on the model-view architecture, usually withQAbstractItemModelSubclasses of  (such asQStandardItemModelor custom model) to use together. I will introduce it in detail belowQTreeViewThe main features and how to use them.

1. Basic concepts

  • Tree view: Controls used to display hierarchical data.
  • Model-View ArchitectureQTreeViewUse the model-view architecture, whereQTreeViewis the view part, responsible for displaying data; and the model (such asQStandardItemModel) is responsible for managing data.
  • node: The basic unit in a tree structure, each node can have child nodes.
  • Root node: The topmost node of the tree structure.
  • Expand/fold: Controls the display status of a node, displays its children when expanded, and hides its children when collapsed.
  • Select Mode: Controls how users select nodes.
  • Editing mode: Allows users to edit data directly in the tree view.

2. Create a QTreeView instance

To useQTreeView, first you need to import the corresponding library:

from  import QApplication, QTreeView, QVBoxLayout, QWidget, QPushButton
from  import QStandardItemModel, QStandardItem
# orfrom  import QApplication, QTreeView, QVBoxLayout, QWidget, QPushButton
from  import QStandardItemModel, QStandardItem

Then create a window and add itQTreeViewControl:

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        ("My Application")
        (100, 100, 800, 600)
      
        # Initialize the UI        ()
  
    def initUI(self):
        layout = QVBoxLayout()
      
        # Create a tree view        self.tree_view = QTreeView(self)
      
        # Create a model         = QStandardItemModel()
        (['name', 'type'])
      
        # Add data        root_item = ()
        item1 = QStandardItem('Project 1')
        ([QStandardItem('Sub-item 1.1'), QStandardItem('Type A')])
        ([QStandardItem('Subproject 1.2'), QStandardItem('Type B')])
        root_item.appendRow(item1)
      
        item2 = QStandardItem('Project 2')
        ([QStandardItem('Subproject 2.1'), QStandardItem('Type C')])
        ([QStandardItem('Subproject 2.2'), QStandardItem('Type D')])
        root_item.appendRow(item2)
      
        # Set the model to view        self.tree_view.setModel()
      
        # Add button        button = QPushButton("Print Selected", self)
        (self.print_selection)
      
        # Add to layout        (self.tree_view)
        (button)
      
        (layout)
  
    def print_selection(self):
        selected_indices = self.tree_view.selectedIndexes()
        for index in selected_indices:
            row = ()
            column = ()
            value = ()
            print(f"OK: {row}, List: {column}, value: {value}")

if __name__ == "__main__":
    app = QApplication([])
    window = MyWindow()
    ()
    ()

3. Common properties and methods of QTreeView

property

  • model: Get or set the currently used model.
  • selectionModel: Get or set the current selection model.
  • currentIndex: Get or set the currently selected index.
  • header: Get the header.
  • rootIndex: Get or set the root index.
  • alternatingRowColors: Get or set whether to alternate row colors.
  • showGrid: Get or set whether to display grid lines.
  • gridStyle: Get or set the grid line style.
  • wordWrap: Get or set whether to enable automatic line wrapping.
  • resizeMode: Get or set the resize mode.
  • selectionBehavior: Gets or sets the selection behavior (selects a cell, row, or column).
  • selectionMode: Get or set the selection mode (single or multiple choice).
  • editTriggers: Get or set the edit trigger.
  • toolTip: Get or set tooltip text.
  • statusTip: Get or set the status bar prompt text.

method

  • setModel(QAbstractItemModel): Set the current model used.
  • model() -> QAbstractItemModel: Get the currently used model.
  • setSelectionModel(QItemSelectionModel): Set the current selection model.
  • selectionModel() -> QItemSelectionModel: Get the current selection model.
  • setCurrentIndex(QModelIndex): Set the currently selected index.
  • currentIndex() -> QModelIndex: Get the currently selected index.
  • header() -> QHeaderView: Get the header.
  • setRootIndex(QModelIndex): Set the root index.
  • rootIndex() -> QModelIndex: Get the root index.
  • setAlternatingRowColors(bool): Set whether to alternate row colors.
  • alternatingRowColors() -> bool: Determine whether colors alternately.
  • setShowGrid(bool): Set whether to display grid lines.
  • showGrid() -> bool: Determine whether grid lines are displayed.
  • setGridStyle(): Set grid line style.
  • gridStyle() -> : Get grid line style.
  • setWordWrap(bool): Set whether to enable automatic line wrapping.
  • wordWrap() -> bool: Determine whether to enable automatic line wrapping.
  • setResizeMode(): Set the resize mode.
  • resizeMode() -> : Get the resize mode.
  • setSelectionBehavior(): Set selection behavior.
  • selectionBehavior() -> : Get selection behavior.
  • setSelectionMode(): Set the selection mode.
  • selectionMode() -> : Get the selection mode.
  • setEditTriggers(): Set the edit trigger.
  • editTriggers() -> : Get the edit trigger.
  • setToolTip(str): Set the tooltip text.
  • toolTip() -> str: Get tooltip text.
  • setStatusTip(str): Set the status bar prompt text.
  • statusTip() -> str: Get the status bar prompt text.
  • expand(QModelIndex): Expand the node with the specified index.
  • collapse(QModelIndex): collapses the nodes of the specified index.
  • expandAll(): Expand all nodes.
  • collapseAll(): Collapse all nodes.
  • selectRow(int): Select the specified row.
  • selectColumn(int): Select the specified column.
  • clearSelection(): Clear selection.
  • selectAll():Select all.
  • selectedIndexes() -> List[QModelIndex]: Get all selected indexes.
  • resizeColumnToContents(int column): Adjust the specified column width according to the content.
  • resizeRowToContents(int row): Adjust the specified row height according to the content.
  • hideColumn(int column): Hide the specified column.
  • showColumn(int column): Displays the specified column.
  • hideRow(int row): Hide the specified line.
  • showRow(int row): Displays the specified row.

4. Detailed examples

Set up the model

# Create a modelmodel = QStandardItemModel()
(['name', 'type'])

# Add dataroot_item = ()
item1 = QStandardItem('Project 1')
([QStandardItem('Sub-item 1.1'), QStandardItem('Type A')])
([QStandardItem('Subproject 1.2'), QStandardItem('Type B')])
root_item.appendRow(item1)

item2 = QStandardItem('Project 2')
([QStandardItem('Subproject 2.1'), QStandardItem('Type C')])
([QStandardItem('Subproject 2.2'), QStandardItem('Type D')])
root_item.appendRow(item2)

# Set the model to viewtree_view.setModel(model)

Get the currently selected index

def print_selection():
    selected_indices = tree_view.selectedIndexes()
    for index in selected_indices:
        row = ()
        column = ()
        value = ()
        print(f"OK: {row}, List: {column}, value: {value}")

Expand and collapse nodes

# Expand the node with the specified indextree_view.expand(tree_view.model().index(0, 0))

# collapse the nodes of the specified indextree_view.collapse(tree_view.model().index(0, 0))

# Expand all nodestree_view.expandAll()

# collapse all nodestree_view.collapseAll()

Select a row or column

# Select Line 1tree_view.selectRow(1)

# Select Column 2tree_view.selectColumn(2)

Clear Selection

tree_view.clearSelection()

Select all

tree_view.selectAll()

Adjust column width and row height according to content

# Adjust the width of column 1 according to the contenttree_view.resizeColumnToContents(1)

# Adjust the height of line 1 according to the contenttree_view.resizeRowToContents(1)

Hide and show columns or rows

# Hide column 2tree_view.hideColumn(2)

# Show column 2tree_view.showColumn(2)

# Hide Line 3tree_view.hideRow(3)

# Show line 3tree_view.showRow(3)

Enable or disable sorting

tree_view.setSortingEnabled(True)  # Enable sortingtree_view.setSortingEnabled(False)  # Disable sorting

Set selection behavior

tree_view.setSelectionBehavior()  # Select the entire linetree_view.setSelectionBehavior()  # Select the entire columntree_view.setSelectionBehavior()  # Select a cell

Set selection mode

tree_view.setSelectionMode()  # Single choicetree_view.setSelectionMode()  # Continuous multiple selectionstree_view.setSelectionMode()  # Extended Multiple Choicetree_view.setSelectionMode()  # Multiple choices

Setting up edit triggers

tree_view.setEditTriggers( | )  # Double-click or select and click Edit

Setting up tooltips and status bar tips

tree_view.setToolTip("This is a tree view")
tree_view.setStatusTip("View and edit data")

5. Signal and slot mechanism

QTreeViewSupports a variety of signals, which can be transmitted during user interaction. Common signals includeclickeddoubleClickedpressedactivatedandselectionChanged. You can handle user input events by connecting these signals to slot functions.

def on_clicked(index):
    row = ()
    column = ()
    value = ()
    print(f"Click: OK: {row}, List: {column}, value: {value}")

def on_double_clicked(index):
    row = ()
    column = ()
    value = ()
    print(f"double click: OK: {row}, List: {column}, value: {value}")

def on_pressed(index):
    row = ()
    column = ()
    value = ()
    print(f"Press: OK: {row}, List: {column}, value: {value}")

def on_activated(index):
    row = ()
    column = ()
    value = ()
    print(f"activation: OK: {row}, List: {column}, value: {value}")

def on_selection_changed(selected, deselected):
    print("Select changes")

tree_view.(on_clicked)
tree_view.(on_double_clicked)
tree_view.(on_pressed)
tree_view.(on_activated)
tree_view.selectionModel().(on_selection_changed)

6. Custom styles

In addition to using built-in style settings, you can also customize it through stylesheets (QSS).QTreeViewAppearance. Stylesheets are similar to CSS and provide powerful style control capabilities.

tree_view.setStyleSheet("""
    QTreeView {
        background-color: #f0f0f0;
        alternate-background-color: #e0e0e0;
        selection-background-color: #0078d7;
        selection-color: white;
        gridline-color: #cccccc;
        border: 1px solid #cccccc;
    }
    QTreeView::item {
        padding: 5px;
    }
    QTreeView::item:selected {
        background-color: #0078d7;
        color: white;
    }
    QTreeView::item:hover {
        background-color: #d0d0d0;
    }
    QTreeView::item:focus {
        outline: none;
    }
    QHeaderView::section {
        background-color: #e0e0e0;
        border: 1px solid #cccccc;
        padding: 5px;
    }
    QHeaderView::section:checked {
        background-color: #0078d7;
        color: white;
    }
""")

7. Dynamic updates and controls

You can update dynamicallyQTreeViewcontent, or control its behavior based on certain conditions. For example, update the data of the tree view when a timer or other event is triggered.

import time
from  import QTimer

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        ("My Application")
        (100, 100, 800, 600)
      
        # Initialize the UI        ()
      
        # Create a timer         = QTimer(self)
        (self.update_tree_view)
        (5000)  # Trigger every 5 seconds  
    def initUI(self):
        layout = QVBoxLayout()
      
        # Create a tree view        self.tree_view = QTreeView(self)
      
        # Create a model         = QStandardItemModel()
        (['name', 'type'])
      
        # Add data        root_item = ()
        item1 = QStandardItem('Project 1')
        ([QStandardItem('Sub-item 1.1'), QStandardItem('Type A')])
        ([QStandardItem('Subproject 1.2'), QStandardItem('Type B')])
        root_item.appendRow(item1)
      
        item2 = QStandardItem('Project 2')
        ([QStandardItem('Subproject 2.1'), QStandardItem('Type C')])
        ([QStandardItem('Subproject 2.2'), QStandardItem('Type D')])
        root_item.appendRow(item2)
      
        # Set the model to view        self.tree_view.setModel()
      
        # Add to layout        (self.tree_view)
      
        (layout)
  
    def update_tree_view(self):
        # Update model data        ()
        (['name', 'type'])
      
        # Add new data        root_item = ()
        item1 = QStandardItem('project1 (renew)')
        ([QStandardItem('子project1.1 (renew)'), QStandardItem('Type A')])
        ([QStandardItem('子project1.2 (renew)'), QStandardItem('Type B')])
        root_item.appendRow(item1)
      
        item2 = QStandardItem('project2 (renew)')
        ([QStandardItem('子project2.1 (renew)'), QStandardItem('Type C')])
        ([QStandardItem('子project2.2 (renew)'), QStandardItem('Type D')])
        root_item.appendRow(item2)

if __name__ == "__main__":
    app = QApplication([])
    window = MyWindow()
    ()
    ()

Summarize

QTreeViewIt is a very powerful and flexible control in PyQt6/PySide6, suitable for various scenarios where tree structure data needs to be displayed and edited. By setting different properties and using style sheets, you can create a rich and diverse tree view style. At the same time, through the signal and slot mechanism, you can easily handle user input events. I hope the above content can help you better understand and apply itQTreeView, and be able to create feature-rich and user-friendly tree view controls based on specific needs.

This is the end of this article about the implementation of the QTreeView class in PyQt6/PySide6. For more related contents of the PyQt6/PySide6 QTreeView class, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!

  • PyQt6
  • QTreeView class

Related Articles

  • Detailed explanation of how to use Python for automated testing

    This article mainly introduces a detailed explanation of how to use Python for automated testing. The example code is introduced in this article in detail, which has a certain reference learning value for everyone's learning or work. Friends who need it, please learn with the editor below.
    2021-01-01
  • A brief introduction to the JSON module in Python

    This article mainly introduces the JSON module in Python, including the preliminary conversion from Python data format to JSON format, etc. If you need it, please refer to it.
    2015-04-04
  • Tkinter canvas parameters, delete components, and add vertical scroll bars for detailed explanation

    This article mainly introduces Python tkinter canvas parameters, delete components, and add vertical scroll bar usage examples. The article introduces the example code in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it
    2021-10-10
  • A summary of python implementation of various binary conversion

    This article mainly summarizes the relevant information for Python to implement various binary conversions, including string and hexadecimal conversion, built-in function hex() and binary conversion, etc. Friends who need it can refer to it, let’s take a look together below.
    2017-06-06
  • Detailed explanation of the method of obtaining content under specific tags by BeautifulSoup

    This article mainly introduces a detailed explanation of the method of obtaining content under specific tags by BeautifulSoup. The article introduces the sample code in detail, which has a certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.
    2020-12-12
  • Make your own starry sky with Python's Turtle

    This article mainly introduces the use of Python's Turtle to make your own starry sky. This article uses the turtle drawing package, which is a very powerful built-in package. Friends who need it can refer to it.
    2023-04-04
  • Exit, return, () and other usage examples and differences in Python

    This article mainly introduces the use examples and differences of exit, return, () and other usage in Python. This article is a summary of an actual project. Friends who need it can refer to it.
    2015-05-05
  • Use yaml configuration file in pytest+request framework

    The pytest+request framework write interface test automation, and using yaml file configuration is more convenient to manage data in use cases. This article mainly introduces the use of yaml configuration files in the pytest+request framework, which has certain reference value. Those who are interested can learn about it.
    2024-01-01
  • Python calls API to implement intelligent reply robot

    This article mainly introduces in detail to you the Python calling API to implement intelligent reply robots, which have certain reference value. Interested friends can refer to it.
    2018-04-04
  • How to solve errors in Python3 UnicodeDecodeError

    When we use Python3 to process text, a very common problem is UnicodeDecodeError. The editor of this article will talk in depth about how this error came about and how to solve it.
    2025-03-03

Latest Comments