根据QTreeView创建树形目录

来源:互联网 发布:java中级工程师考试 编辑:程序博客网 时间:2024/05/23 02:21

//=================================================

MyTreeView.h

#pragma once

#include <QtGui/QtGui>
class MyTreeView : public QWidget
{
Q_OBJECT
public:
MyTreeView();
~MyTreeView();
private:
QDirModel *model;
QTreeView *treeView;
private slots:
void mkdir();
void rm();
};


//==============================================

MyTreeView.cpp


#include "MyTreeView.h"
#include <QtCore/QTextStream>
#include <QtCore/QFile>




MyTreeView::MyTreeView(void)
{
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());
QModelIndex index = model->index("C:/test");
//自动展开当前目录
treeView->expand(index);
treeView->scrollTo(index);
//列宽自动适应内容
treeView->resizeColumnToContents(0);
//横向控件集绑定两个按钮控件
QHBoxLayout *btnLayout = new QHBoxLayout;
QPushButton *createBtn = new QPushButton("Create Directory");
QPushButton *deleteBtn = new QPushButton("remove");
btnLayout->addWidget(createBtn);
btnLayout->addWidget(deleteBtn);
//纵向控件集绑定树列表控件
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(treeView);
mainLayout->addLayout(btnLayout);
this->setLayout(mainLayout);
//信号槽设定
connect(createBtn, SIGNAL(clicked()), this, SLOT(mkdir()));
connect(deleteBtn, SIGNAL(clicked()), this, SLOT(rm()));
}


MyTreeView::~MyTreeView(void)
{
}


void MyTreeView::mkdir()
{
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
{
//当前目录或文件无效时,直接返回
return;
}
//获取文件目录名
QString dirName = QInputDialog::getText(this,"Create Directory","Directory name");
//目录名不为空时,创建目录
if (!dirName.isEmpty())
{
//创建失败时,弹出消息
if (!model->mkdir(index, dirName).isValid())
{
QMessageBox::information(this,"Create Directory","Failed to create the directory");
}
}
}
void MyTreeView::rm()
{
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
{
//目录或文件无效时,直接返回
return;
}
bool nok;
if (model->fileInfo(index).isDir())
{
//删除目录
nok = model->rmdir(index);
} else
{
//删除文件
nok = model->remove(index);
}
if (!nok)
{
//若删除失败,弹出提示消息
QMessageBox::information(this,"Remove",QString("Failed to remove %1").arg(model->fileName(index)));
}
}


//========================================================================

main.cpp

#include <QtGui/QApplication>
#include "MyTreeView.h"


int main(int argc, char *argv[])
{
QApplication a(argc, argv);


MyTreeView tvw;
tvw.setWindowTitle("TreeView");
tvw.show();
return a.exec();
}


//===================================================

如果界面想支持中文字符,只需在main.cpp中将本地字符中文化即可。


//===================================================

运行效果如下:


原创粉丝点击