首先,我们来看一个很有用的model:QDirModel。这个model允许我们在view中显示操作系统的目录结构,

当然我们肯定要用到QTreeView。这次让我们先来看看运行结果:

QT做一个硬盘目录视图QTreeView,QDirModel_#include

首先,我们要建立一个QT的项目,然后呢点击项目属性,添加新文件,选择c++ Class,点击Choose输入一个类名,

接着在.h文件里面添加要用到的类

#ifndef MYTREEVIEW_H

#define MYTREEVIEW_H
#include <QWidget>
#include <QDirModel>
#include <QTreeView>
#include <QMainWindow>
class MyTreeView :public QWidget
{
Q_OBJECT
public:
MyTreeView();//构造
private:
QDirModel *model;//定义模型变量
QTreeView *treeView;//定义树视图
private slots:
void mkdir();
void rm();
};
#endif // MYTREEVIEW_H
接着就在.cpp文件里面去写代码了:

#include "mytreeview.h"

#include <QTreeView>
#include <QHeaderView>
#include <QHBoxLayout>//布局类
#include <QString>//文本类
#include <QPushButton>
#include <QInputDialog>
#include <QMessageBox>//
MyTreeView::MyTreeView()
{
model = new QDirModel;//模型
model->setReadOnly(false);//设置为只读
model->setSorting(QDir::DirsFirst | QDir::IgnoreCase | QDir::Name);//排序
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);
QHBoxLayout *btnLayout = new QHBoxLayout;
QPushButton *createBtn = new QPushButton(tr("Create Directory..."));
QPushButton *delBtn = new QPushButton(tr("Remove"));
btnLayout->addWidget(createBtn);
btnLayout->addWidget(delBtn);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(treeView);
mainLayout->addLayout(btnLayout);
this->setLayout(mainLayout);
connect(createBtn, SIGNAL(clicked()), this, SLOT(mkdir()));
connect(delBtn, SIGNAL(clicked()), this, SLOT(rm()));
}
void MyTreeView::mkdir()
{
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 MyTreeView::rm()
{
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文件里面

MyTreeView b;

b.show();
就可以了