Qt QDirModel实现文件的管理

1) dialogimpl.h

#ifndef DIALOGIMPL_H
#define DIALOGIMPL_H
//
#include <QDialog>
#include "ui_dialog.h"
#include "QVBoxLayout"
#include "QHBoxLayout"
#include "QTreeView"
#include "QDirModel"
#include "QPushButton"
#include "QInputDialog"
#include "QMessageBox"
//
class DialogImpl : public QDialog, public Ui::Dialog
{
Q_OBJECT
public:
 DialogImpl( QWidget * parent = 0, Qt::WFlags f = 0 );
private slots:
 void mkdir();
 void rm();
private:
 QVBoxLayout *mainLayout;
 QTreeView *treeView;
 QDirModel *model;
};
#endif

2) dialogimpl.cpp

#include "dialogimpl.h"
//
DialogImpl::DialogImpl( QWidget * parent, Qt::WFlags f)
 : QDialog(parent, f)
{
 setupUi(this);
 this->setWindowTitle("QDirModel Demo");
 this->setFixedSize(800,500);
 mainLayout=new QVBoxLayout;
 model=new QDirModel;
 model->setReadOnly(false);
 
 treeView=new QTreeView;
 treeView->setModel(model);
 treeView->setSortingEnabled(true);
 
 //get the current path's index
 QModelIndex index = model->index(QDir::currentPath());
 //Expand it's parent model item specified by the index
 treeView->scrollTo(index);
 //Expands the model item specified by the index.
 treeView->expand(index);
 //Resizes the column given to the size of its contents.
 treeView->resizeColumnToContents(0);

 
 QHBoxLayout *btnLayout=new QHBoxLayout;
 QPushButton *createBtn=new QPushButton(tr("create"));
 QPushButton *delBtn=new QPushButton(tr("delete"));
 btnLayout->addWidget(createBtn);
 btnLayout->addWidget(delBtn);
 
 mainLayout->addWidget(treeView);
 mainLayout->addLayout(btnLayout);
 setLayout(mainLayout);
 
 connect(createBtn,SIGNAL(clicked()),this,SLOT(mkdir()));
 connect(delBtn,SIGNAL(clicked()),this,SLOT(rm()));
}
//create directoy
void DialogImpl::mkdir()
{
 QModelIndex index=treeView->currentIndex();
 if(!index.isValid())
 {
  return;
 }
 QString dirName=QInputDialog::getText(this,"create directory","directory name");
 if(!dirName.isEmpty())
 {
  //Create a directory with the name in the parent model item
  if(!model->mkdir(index,dirName).isValid())
  {
   QMessageBox::information(this,"create directory","failure to create the directory");
  }
 }
}
//remove directory
void DialogImpl::rm()
{
 QModelIndex index=treeView->currentIndex();
 if(!index.isValid())
 {
  return;
 }
 int ret = QMessageBox::question(this, tr("remove"),tr("are sure to remove?"),
    QMessageBox::Yes | QMessageBox::No,QMessageBox::No);
 if(ret==QMessageBox::Yes)
 {
  bool ok;
  //Returns true if this object points to a directory or to a symbolic link to a directory
  if(model->fileInfo(index).isDir())
  {
   ok=model->rmdir(index);//deletes the directory from the file system
  }
  else
  {
   ok=model->remove(index);//deletes the file from the file system
  }
  if(!ok)
  {
   QMessageBox::information(this,"remove",tr("failure to remove %1").arg(model->fileName(index)));
  }
 }
}

 

你可能感兴趣的:(Qt QDirModel实现文件的管理)