This time I studied the usage of QTreeView, so I want to use QTreeView to display all subdirectories and files under the specified directory. During the process, I encountered a few problems. I will record them here and share them with you. If there is anything wrong, please criticize and correct me:
- After setting the root directory, all the directories in the system will still be displayed, as shown in the figure below:
For this problem, the solution is relatively simple, just set the RootPath and RootIndex for the QTreeView at the same time
self._home = "F:/FileProtect/"
self.filemodel.setRootPath(self._home)
self.treeView.setModel(self.filemodel)
self.treeView.setRootIndex(self.filemodel.index(self._home))
- After using QStandardItemModel to obtain the file directory, the Header of QTreeView displays the English header, as shown in the figure:
To solve this problem, I made multiple attempts, but all failed. First,
consider modifying headData in QFileSystemModel, and the result is that this method does not take effect.
self.filemodel.setHeaderData(0, Qt.Horizontal, '文件名', 0)
self.filemodel.setHeaderData(1, Qt.Horizontal, '大小', 0)
self.filemodel.setHeaderData(2, Qt.Horizontal, '文件类型', 0)
self.filemodel.setHeaderData(3, Qt.Horizontal, '修改时间', 0)
Finally found a way, it feels cumbersome, but it works. If any friend has a better method, please share it. The following introduces my method here.
First, get the header of QTreeView, then create a QStandardItemModel, and only set the headerData, and then set the Model of the header to QStandardItemModel. Here is a point to note: set the Model of the header must be after setting the Model for QTreeView
The complete code is as follows:
self._home = "F:/FileProtect/"
self.filemodel = QFileSystemModel()
self.filemodel.setFilter(QtCore.QDir.Dirs | QtCore.QDir.Files | QtCore.QDir.NoDotAndDotDot)
self.filemodel.setRootPath(self._home)
self.treeView.setModel(self.filemodel) # 设置QTreeView的Model
self.headerModel = QStandardItemModel()
self.headerModel.setColumnCount(4) # 设置model的列数
self.headerModel.setHeaderData(0, Qt.Horizontal, '文件名', 0)
self.headerModel.setHeaderData(1, Qt.Horizontal, '大小', 0)
self.headerModel.setHeaderData(2, Qt.Horizontal, '文件类型', 0)
self.headerModel.setHeaderData(3, Qt.Horizontal, '修改时间', 0)
header = self.treeView.header()
header.setModel(self.headerModel) # 设置QTreeView#Header的Model
self.treeView.setRootIndex(self.filemodel.index(self._home)) # 设置RootIndex
The final running effect is as follows: