pyqt中的目錄QFileSystemModel 內容用 QTreeView 顯示

HockerF發表於2020-09-28

前兩天做程式碼的時候自己實現了一個目錄展示的效果,雖然有較強的擴充套件性,但是官方可能還是要完善一些。

經過幾個小時的摸索,大概效果如下:

import sys, os
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout, QDirModel

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
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 tree_cilcked(self, Qmodelidx):
        print(self.model.filePath(Qmodelidx))
        print(self.model.fileName(Qmodelidx))
        print(self.model.fileInfo(Qmodelidx))
        
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        # 這裡得到目錄結構
        self.model = QFileSystemModel()
        self.model.setRootPath(QDir.currentPath())
        # 這裡過濾,只顯示 py 檔案
        mf = self.model.setNameFilters(['*.py'])
        self.model.setNameFilterDisables(False)
        # 這裡做展示
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setRootIndex(self.model.index(QDir.currentPath()))
        self.tree.doubleClicked.connect(self.tree_cilcked)
        # 這裡隱藏了目錄資訊展示
        for i in [1,2,3]:
            self.tree.setColumnHidden(i, True)
		# 縮排
        self.tree.setIndentation(10)
        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()

效果:
在這裡插入圖片描述

相關文章