PyQt5 qtreeview

QTreeView implements a tree display of the entries in a Model. It is one of the Model-View classes and is part of the Qt Model-View framework.

It implements the interface defined by the QAbstractItemView class and is therefore able to display data provided by models derived from the QAbstractItemModel class.

The model-view architecture ensures that the contents of the tree view are updated as the model is changed. Its table headers are created by the QHeaderView class.

qtreeview model

A common example is the use of data provided by QFileSystemModel, displayed as a tree view, for browsing directories and files on the computer’s local system.

fileModel = QFileSystemModel()
treeView = QTreeView(self)

QTreeView common methods.

  • setModel(): sets the model used.
  • setHeader(): sets the table header.
  • header(): get the table header object.
  • indexAbove(): get the index in front of the specified index.
  • indexBelow(): get the index after the specified index; indexBelow(): get the index after the specified index; indexBelow(): get the index after the specified index
  • collapse(): collapses the entries of the specified index.
  • collapseAll(): collapses the entire tree view.
  • expand(): expands the entries of the specified index.
  • expandAll(): expand the whole tree view.

QTreeView common signals.

  • collapsed: emitted when the collapse operation is completed.
  • expanded: emitted when the expand operation is completed.

QTreeView example

The test code uses QStandardItemModel as the model for the tree view, demonstrates how to use the tree view to display model data, adjusts the column width to ensure that the textual information of the entry is displayed in its entirety.

It shows how to add dashed connections between nodes, demonstrates how to add checkbox buttons before an entry, and how to get information about itself when an entry is selected, information about its parent class, and information of neighboring entries.

The complete code is as follows:

import sys

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt,QModelIndex
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTreeView, QAbstractItemView, QHeaderView, QStyleFactory)

class DemoTreeView(QMainWindow):

    def __init__(self, parent=None):
        super(DemoTreeView, self). __init__(parent)   
         # Set the window title
        self.setWindowTitle('QTreeView example oneminutepython.com')      
        # Set the window size
        self.resize(600, 400)

    def initUi(self):
        # Set the table header information
        model = QStandardItemModel(self)
        model.setHorizontalHeaderLabels(['ItemName', 'Info'])
        # Add the item
        itemProject = QStandardItem('Item')
        model.setItem(0, 1, QStandardItem('Project Description'))
        # Add child items
        itemChild = QStandardItem('Folder1')
        itemProject.setChild(0, 1, QStandardItem('Description'))
        # Continue adding
        itemFolder = QStandardItem('Folder2')
        for group in range (5):
            itemGroup = QStandardItem('group{}'.format(group+1))
            for ch in range (group+1):
                itemCh = QStandardItem('member{}'.format(ch+1))
                # Add checkboxes
                itemGroup.setChild(itemCh.index().row(), 1, QStandardItem('Member {} information description'.format(ch+1)))
        itemProject.setChild(itemFolder.index().row(), 1, QStandardItem('Folder 2 info description'))
        treeView = QTreeView(self)
        #Adjust the width of the first column
        treeView.header().resizeSection(0, 160)
        #set to have a dashed connection
        #Show information about the selected rows
        self.model = model
        self.treeView = treeView

    def onCurrentChanged(self,current, previous):
        txt = 'parent:[{}] '.format(str(current.parent().data()))
        txt += 'Current selection:[(row{},column{})] '.format(current.row(), current.column())
        if current.column() == 0:
            name = str(current.data())
            info = str(current.sibling(current.row(), 1).data())
            name = str(current.sibling(current.row(), 0).data())
            info = str(current.data())
        txt += 'name:[{}] info:[{}]'.format(name, info)    

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DemoTreeView()

The result of the run is as follows.

pyqt qtreeview