我正在从指定的文件夹目录填充QTreeview。但是我并不完全清楚如何正确调整代码以使Treeview更好地反映文件夹的嵌套。在这种情况下,我只想显示包含OBJ文件的文件夹。
我希望它看起来像这样
import os, sys
from Qt import QtGui, QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.resize(350,500)
self.ui_navigator = QtWidgets.QComboBox()
self.ui_files = QtWidgets.QTreeView()
self.ui_files.setHeaderHidden(True)
self.ui_files.setModel(QtGui.QStandardItemModel())
self.ui_files.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.ui_files.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.ui_files.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
self.setCentralWidget(self.ui_files)
self.populate_files()
def populate_files(self, files=[]):
model = self.ui_files.model()
model.clear()
root = 'C:/Users/jmartini/Desktop/Trash/models'
for subdir, dirs, files in os.walk(root):
folder_item = QtGui.QStandardItem(os.path.basename(subdir).upper())
folder_item.setData(subdir, role=QtCore.Qt.UserRole)
folder_item.setData(QtGui.QColor(QtGui.QColor(200, 140, 70, 255)), role=QtCore.Qt.ForegroundRole)
fnt = folder_item.font()
fnt.setBold(True)
folder_item.setData(fnt, role=QtCore.Qt.FontRole)
model.appendRow(folder_item)
for file in files:
if file.lower().endswith('.obj'):
filepath = os.path.join(subdir, file)
name = os.path.basename(file)
item = QtGui.QStandardItem(name)
item.setData(filepath, role=QtCore.Qt.UserRole)
folder_item.appendRow(item)
model.sort(0, QtCore.Qt.AscendingOrder)
def main():
app = QtWidgets.QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
答案 0 :(得分:0)
使用QFileInfo
和QDir
:
def populate_files(self):
model = self.ui_files.model()
model.clear()
exts = ["*.obj"]
root = 'C:/Users/jmartini/Desktop/Trash/models'
def addItems(parent, path):
finfo = QtCore.QFileInfo(path)
if finfo.isFile():
if "*."+finfo.suffix() in exts:
it = QtGui.QStandardItem(finfo.fileName())
it.setData(finfo.absoluteFilePath(), QtCore.Qt.UserRole)
parent.appendRow(it)
elif finfo.isDir():
iterator = QtCore.QDirIterator(finfo.absoluteFilePath(), exts, QtCore.QDir.Files, QtCore.QDirIterator.Subdirectories)
if iterator.hasNext():
it = QtGui.QStandardItem(finfo.fileName().upper())
it.setData(finfo.absoluteFilePath(), QtCore.Qt.UserRole)
parent.appendRow(it)
for subfiles in QtCore.QDir(finfo.absoluteFilePath()).entryInfoList([], QtCore.QDir.AllEntries|QtCore.QDir.NoDotAndDotDot):
addItems(it, subfiles.absoluteFilePath())
for finfo in QtCore.QDir(root).entryInfoList([], QtCore.QDir.AllEntries|QtCore.QDir.NoDotAndDotDot):
addItems(model, finfo.absoluteFilePath())
self.ui_files.expandAll()