QFileSystemModel

来源:互联网 发布:java集合面试题 编辑:程序博客网 时间:2024/06/06 03:05

QFileSystemModel 的作用是维护一个目录的信息。因此,它不需要保存数据本身,而是保存这些在本地文件系统中的实际数据的一个索引。
这与 QStandardItemModel 不同,QStandardItemModel 能够让列表、表格、树等视图显示不同的数据结构,这种Model 会保存实际数据。

Demo

#include "Widget.h"#include "ui_Widget.h"Widget::Widget(QWidget *parent) :    QWidget(parent),    ui(new Ui::Widget){    ui->setupUi(this);    model = new QFileSystemModel;    model->setRootPath(QDir::currentPath());    treeView = new QTreeView(this);    treeView ->setModel(model);    treeView->setRootIndex(model->index(QDir::currentPath()));    treeView->header()->setStretchLastSection(true);    treeView->header()->setSortIndicator(0,Qt::AscendingOrder);    treeView->header()->setSortIndicatorShown(true);    treeView->header()->setHidden(false);    treeView->header()->setSectionsClickable(true);    QPushButton *mkDirButton = new QPushButton(tr("make Directory"),this);    QPushButton *rmDirButton = new QPushButton(tr("remove"),this);    QHBoxLayout *buttonLayout = new QHBoxLayout;    buttonLayout->addWidget(mkDirButton);    buttonLayout->addWidget(rmDirButton);    QVBoxLayout *layout = new QVBoxLayout;    layout->addWidget(treeView);    layout->addLayout(buttonLayout);    this->setLayout(layout);    this->setWindowTitle("QFileSystemModel");    connect(mkDirButton,SIGNAL(clicked(bool)),this,SLOT(mkDir(bool)));    connect(rmDirButton,SIGNAL(clicked(bool)),this,SLOT(rm(bool)));}void Widget::mkDir(bool){    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 Widget::rm(bool){    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)));}Widget::~Widget(){    delete ui;}

如果没有 treeView->setRootIndex(model->index(QDir::currentPath())); 则显示的并不当前路径,而是整个文件系统的目录。

这里不需要十分担心 QFileSystemModel 的性能问题,因为它会启动自己的线程进行文件夹扫描,不会发生因扫描文件夹而导致的主线程阻塞的现象。另外需要注意的是,QFileSystemModel 会对模型的结果进行缓存,如果想要立即刷新结果,需要通知 QFileSystemWatcher 类。

文章转载自:http://www.qter.org/forum.php?mod=viewthread&tid=665, 原作者:devbean

0 0
原创粉丝点击