Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk5 min

PyQt6 QTreeView Tutorial: Models, Files, Checkboxes, and Search

Learn how PyQt6 QTreeView works with models, add checkboxes, show local files with QFileSystemModel, and filter a tree from a search field.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In PyQt6, QTreeView displays hierarchical data supplied by a model; it does not store the tree itself. Use QStandardItemModel for a straightforward in-memory tree, QFileSystemModel for local files and folders, and QSortFilterProxyModel when you need to sort or filter what the view shows. The examples below connect those pieces and explain what you must implement for checkboxes and useful tree search.

How QTreeView fits into Qt’s model/view architecture

Qt separates the data from its presentation. A model exposes data and its hierarchy; a view such as QTreeView presents that data and handles interaction such as selection and expansion. A delegate supplies standard item presentation and editing behavior, including the checkbox control for checkable items.

This separation matters when an application has more than one way to display or manipulate the same data: the model remains the source of truth rather than each view keeping a separate copy. A tree appears only when the model represents parent-child relationships. A flat model does not become hierarchical just because it is attached to QTreeView. See the Qt model/view programming overview and QTreeView documentation.

Build an in-memory tree with QStandardItemModel

QStandardItemModel is a convenient general-purpose choice when your application can populate a tree directly. Each QStandardItem can hold display text and other item data, and items can have child rows.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import sys
from PyQt6.QtGui import QStandardItem, QStandardItemModel
from PyQt6.QtWidgets import QApplication, QTreeView

app = QApplication(sys.argv)

model = QStandardItemModel()
model.setHorizontalHeaderLabels(["Name"])

animals = QStandardItem("Animals")
plants = QStandardItem("Plants")

animals.appendRow(QStandardItem("Mammals"))
animals.appendRow(QStandardItem("Birds"))
plants.appendRow(QStandardItem("Trees"))
plants.appendRow(QStandardItem("Flowers"))

model.appendRow(animals)
model.appendRow(plants)

view = QTreeView()
view.setModel(model)
view.setWindowTitle("PyQt6 tree example")
view.show()

sys.exit(app.exec())

The model contains two top-level rows, each with child rows. Calling setModel() connects the view to that hierarchy. For substantial application data that already has its own structure, or needs specialized behavior, a custom QAbstractItemModel subclass can avoid representing everything as a separate collection of standard items.

Add model-backed checkboxes

With standard items, mark an item checkable and initialize its check state. The view’s item machinery presents and edits the checkbox; the state belongs to the model, not to a widget layered over the row.

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QStandardItem

item = QStandardItem("Enable notifications")
item.setCheckable(True)
item.setCheckState(Qt.CheckState.Unchecked)
model.appendRow(item)

Use Qt.CheckState.Checked to initialize it as checked. Read the resulting state from the item/model when application logic needs it.

For a custom model, expose check state through the Qt.ItemDataRole.CheckStateRole data role, provide item flags that allow the item to be enabled and user-checkable, and implement the model’s data-setting behavior so a changed state is stored. Returning a checkbox state without accepting and retaining edits will not provide a functional checkbox.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Checking a parent does not, by itself, mean all children will be checked, nor does Qt automatically calculate a partially checked parent from its descendants. If the interface needs that behavior, add explicit application logic to update descendants and recompute parent states.

Show local files with QFileSystemModel

Use QFileSystemModel when the tree should represent local directories and files. It supplies file-system data to the tree; QTreeView provides the visible hierarchy and interaction.

import sys
from PyQt6.QtWidgets import QApplication, QFileSystemModel, QTreeView

app = QApplication(sys.argv)

model = QFileSystemModel()
model.setRootPath("")

view = QTreeView()
view.setModel(model)
view.setWindowTitle("File system")
view.show()

sys.exit(app.exec())

To limit the visible tree to a chosen folder, set that folder as the model root and use the index returned for it as the view’s root index:

folder = "/path/to/folder"
root_index = model.setRootPath(folder)
view.setRootIndex(root_index)

Replace the example path with a directory available to the application. The model represents local file-system contents; it is not intended as a general-purpose model for unrelated application data. Qt’s QTreeView documentation shows the same model-and-view pairing for a directory tree, and the Qt for Python model/view overview describes the standard models and suitable views.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Filter a tree from a search field

QSortFilterProxyModel sits between a source model and the view. It can filter or sort the source data without replacing that model. Connect the line edit’s text-change signal to the proxy’s filter setter:

from PyQt6.QtCore import QSortFilterProxyModel, Qt
from PyQt6.QtWidgets import QLineEdit

search = QLineEdit()
search.setPlaceholderText("Search names")

proxy = QSortFilterProxyModel()
proxy.setSourceModel(model)
proxy.setFilterCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
proxy.setFilterKeyColumn(0)

view.setModel(proxy)
search.textChanged.connect(proxy.setFilterFixedString)

This basic approach searches the configured column using the proxy’s default filtering behavior. A real tree search needs a deliberate policy: choose which columns and data roles are searchable, whether matching is case-sensitive, and what should happen to the path around a match. For example, a match in a leaf is often useful only if its parent path remains visible. Conversely, a matching parent might or might not be expected to reveal all of its children.

Do not assume every Qt/PyQt6 version exposes identical recursive-filtering options or that a setting has the desired ancestor and descendant behavior. Check the API and test the target runtime. If default filtering does not express the desired tree policy, subclass QSortFilterProxyModel and implement filterAcceptsRow(). Qt documents the proxy model’s filtering role and customization approach in its model/view programming guide and QSortFilterProxyModel documentation.

When application code receives an index from the view while a proxy is installed, that index belongs to the proxy model. Use the proxy’s mapToSource() when you need the corresponding source-model index.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose practical QTreeView behavior

Keep view settings tied to the interface you are building. For example, a directory browser may benefit from expansion and a visible header, while a compact category selector may not need either. Common controls include header visibility, sorting, indentation, expansion, selection, and root decoration.

  • Sorting: Sorting is disabled by default. When populating a QStandardItemModel, insert the items first and enable sorting afterward to avoid sorting work during population.
  • Uniform row heights: Enable this only if every row is guaranteed to have the same height. It is not appropriate when rows may vary in size.
  • Expansion and selection: Use the view’s tree interaction for opening branches and selecting indexes; keep the data and its hierarchy in the model.

See the current QTreeView API reference for the view’s available properties and methods.

Pick the model that matches the data

Need Suitable model What to account for
Directly populated in-memory tree QStandardItemModel Convenient for arbitrary items and checkable state; a large or specialized data structure may suit a custom model better.
Local files and directories QFileSystemModel Represents the local file system rather than general business or application data.
Filtering or sorting another model QSortFilterProxyModel in front of a source model Define tree-search behavior explicitly when default filtering does not retain the paths or branches your users need.
Existing application structure or custom data behavior A custom QAbstractItemModel subclass Implement the required data, hierarchy, flags, and editing behavior for the features the view should expose.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.