用Qt来显示一个文件目录是很简单的,如下:
例子1:查找显示所有的图片
QFileSystemModel *model = new QFileSystemModel(); model->setRootPath("/"); //model->setFilter(QDir::Dirs|QDir::NoDotAndDotDot); //只显示文件夹 // 设置过滤器 QStringList filter; filter << "*.png" << "*.jpg" << "*.bmp" << "*.gif"; model->setNameFilters(filter); // 没有通过过滤器的文件disable还是隐藏,true为disable false为隐藏 model->setNameFilterDisables(false); mTreeView = new QTreeView(); mTreeView->setAnimated(false); mTreeView->setSortingEnabled(true); mTreeView->setModel(model);
2.设置一些特殊属性的过滤 setFilter 如只显示文件夹或系统文件
3.显示项的名字过滤器这个非常有用,如我们想显示所有的"png,jpg,bmp,gif"图片
4.setNameFilterDisables这个效果如下图:
setNameFilterDisables(false)表示不符合名字过滤要求的隐藏而不是disable
例子2:创建一个简单的可以添加文件夹删除文件夹的资源管理
实现也很简单:
model = new QFileSystemModel(); model->setRootPath(QDir::currentPath()); mTreeView = new QTreeView(); mTreeView->setAnimated(false); mTreeView->setSortingEnabled(true); mTreeView->setModel(model); mTreeView->setRootIndex(model->index(QDir::currentPath())); QPushButton* mkdirButton = new QPushButton(tr("Make directory"), this); QPushButton* rmButton = new QPushButton(tr("Remove"), this); QHBoxLayout* buttonLayout = new QHBoxLayout; buttonLayout->addWidget(mkdirButton); buttonLayout->addWidget(rmButton); QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(mTreeView); layout->addLayout(buttonLayout); setLayout(layout); setWindowTitle("File system..."); resize(960,640); //connect(mTreeView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_treeView_doubleClicked(QModelIndex))); connect(mkdirButton, SIGNAL(clicked()), this, SLOT(mkdir())); connect(rmButton, SIGNAL(clicked()), this, SLOT(rm()));
void Dialog::mkdir() { QModelIndex index = mTreeView->currentIndex(); if ( !index.isValid() ) { return; } QString name = QInputDialog::getText(this, tr("Create directory"), tr("Directory name")); if ( !name.isEmpty() ) { if ( !model->isDir(index) ) { index = model->parent(index); } if ( !model->mkdir(index, name).isValid() ) { QMessageBox::information(this, tr("Create directory failed..."), tr("Failed to create directory")); } } }
void Dialog::rm() { QModelIndex index = mTreeView->currentIndex(); if ( !index.isValid() ) { return; } bool ok; QFileInfo info = model->fileInfo(index); if ( info.isDir() ) { ok = model->rmdir(index); } else { ok = model->remove(index); } if ( !ok ) { QMessageBox::information(this, tr("Removed"), tr("Filed to remove %1").arg(model->fileName(index))); } }
工程如下: