python logo

pyqt treeview


Python hosting: Host, run, and code Python in the cloud!

PyQt can show a directory structure using a QTreeView. For the treeview to show as a directory tree, we need to set its model to a QFileSystemModel instance. That is achieved by calling the setModel method for the tree instance.

We can set additional options on the tree object: sorting enabled (setSortingEnabled), animation and indention.

qt5 directory view

Related course:

Example
The code below will add the directory view (QTreeView combined with QFileSystemModel) to a grid window. A layout needs to be set for the widget to be seen.

The path is specified using the models setRootPath() method, where the parameter is the full path to the directory. By default its the root.

For layout we use a qvboxlayout.


import sys
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout
from PyQt5.QtGui import QIcon

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 file system view - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.model = QFileSystemModel()
self.model.setRootPath('')
self.tree = QTreeView()
self.tree.setModel(self.model)

self.tree.setAnimated(False)
self.tree.setIndentation(20)
self.tree.setSortingEnabled(True)

self.tree.setWindowTitle("Dir View")
self.tree.resize(640, 480)

windowLayout = QVBoxLayout()
windowLayout.addWidget(self.tree)
self.setLayout(windowLayout)

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

BackNext





Leave a Reply: