QFileSystemModel的简单用法
参考<<C++ GUI Programming with Qt 4>>中文版第二版中的例子"DirectoryViewer",简单介绍QFileSystemModel的用法,QFileSystemModel 类似QDitModel,只不过Qt不推荐使用QDirModel,推荐是使用QFileSystemModel,该模型允许我们在view中显示操作系统的目录结构。
directoryviewer.h文件:
#ifndef DIRECTORYVIEWER_H #define DIRECTORYVIEWER_H #include <QtGui/QDialog> #include <QFileSystemModel> #include <QTreeView> class DirectoryViewer : public QDialog { Q_OBJECT public: DirectoryViewer(QWidget *parent = 0); ~DirectoryViewer(); private slots: void createDirectory(); void remove(); private: QFileSystemModel *model; QTreeView *treeView; }; #endif
directoryviewer.cpp文件:
#include "directoryviewer.h" #include <QPushButton> #include <QVBoxLayout> #include <QHBoxLayout> #include <QHeaderView> #include <QInputDialog> #include <QMessageBox> DirectoryViewer::DirectoryViewer(QWidget *parent) : QDialog(parent) { model = new QFileSystemModel; model->setReadOnly(false); //设置可以修改 model->setRootPath(QDir::currentPath()); treeView = new QTreeView; treeView->setModel(model); treeView->header()->setStretchLastSection(true); treeView->header()->setSortIndicator(0, Qt::AscendingOrder); treeView->header()->setSortIndicatorShown(true); treeView->header()->setClickable(true); QModelIndex index = model->index(QDir::currentPath()); treeView->expand(index); //当前项展开 treeView->scrollTo(index); //定位到当前项 treeView->resizeColumnToContents(0); QPushButton *createButton = new QPushButton("Create Directory", this); QPushButton *removeButton = new QPushButton("Remove", this); QHBoxLayout *hlayout = new QHBoxLayout; hlayout->addWidget(createButton); hlayout->addWidget(removeButton); QVBoxLayout *vlayout = new QVBoxLayout; vlayout->addWidget(treeView); vlayout->addLayout(hlayout); setLayout(vlayout); connect(createButton, SIGNAL(clicked()), this, SLOT(createDirectory())); connect(removeButton, SIGNAL(clicked()), this, SLOT(remove())); } DirectoryViewer::~DirectoryViewer() { } void DirectoryViewer::createDirectory() { QModelIndex index = treeView->currentIndex(); if (!index.isValid()) { return; } QString dirName = QInputDialog::getText(this, tr("Create Directory"), tr("Directory name")); if (!dirName.isEmpty()) { if (!model->mkdir(index, dirName).isValid()) { QMessageBox::information(this, tr("Create Directory"), tr("Failed to create the directory")); } } } void DirectoryViewer::remove() { QModelIndex index = treeView->currentIndex(); if (!index.isValid()) { return; } bool ok; if (model->fileInfo(index).isDir()) { ok = model->rmdir(index); } else { ok = model->remove(index); } if (!ok) { QMessageBox::information(this, tr("Remove"), tr("Failed to remove %1").arg(model->fileName(index))); } }
main.cpp文件:
#include <QtGui/QApplication> #include "directoryviewer.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); DirectoryViewer w; w.show(); w.setWindowTitle("QFileSystemModel Demo"); return a.exec(); }
运行界面: