(三)使用预定义模型QDirModel的例子

时间:2023-03-08 21:44:17

使用预定义模型QDirModel的例子

Main.cpp

#include <QApplication>
#include "directoryviewer.h" int main(int argc, char *argv[])
{
QApplication app(argc, argv);
DirectoryViewer directoryViewer;
directoryViewer.show();
return app.exec();
}

directoryviewer.h

#ifndef DIRECTORYVIEWER_H
#define DIRECTORYVIEWER_H #include <QDialog> class QDialogButtonBox;
class QDirModel;
class QTreeView; class DirectoryViewer : public QDialog
{
Q_OBJECT public:
DirectoryViewer(QWidget *parent = ); private slots:
void createDirectory();
void remove(); private:
QTreeView *treeView;
QDirModel *model;
QDialogButtonBox *buttonBox;
}; #endif

directoryviewer.cpp

#include <QtGui>

#include "directoryviewer.h"

DirectoryViewer::DirectoryViewer(QWidget *parent)
: QDialog(parent)
{
//创建一个目录模型
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(, Qt::AscendingOrder);
treeView->header()->setSortIndicatorShown(true);
treeView->header()->setClickable(true); //当前目录的模型索引
QModelIndex index = model->index(QDir::currentPath());
//如果需要就打开它的父对象一直到根节点,并且调用scrollTo()滚动倒当前项,确保它是可见的
treeView->expand(index);
treeView->scrollTo(index);
//确保第一列足够宽,可以显示它所有的条目。
treeView->resizeColumnToContents(); buttonBox = new QDialogButtonBox(Qt::Horizontal);
QPushButton *mkdirButton = buttonBox->addButton(
tr("&Create Directory..."), QDialogButtonBox::ActionRole);
QPushButton *removeButton = buttonBox->addButton(tr("&Remove"),
QDialogButtonBox::ActionRole);
buttonBox->addButton(tr("&Quit"), QDialogButtonBox::AcceptRole); connect(mkdirButton, SIGNAL(clicked()),
this, SLOT(createDirectory()));
connect(removeButton, SIGNAL(clicked()), this, SLOT(remove()));
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(treeView);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout); setWindowTitle(tr("Directory Viewer"));
} void DirectoryViewer::createDirectory()
{
//获取当前目录 模型索引
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
//获取创建目录名
QString dirName = QInputDialog::getText(this,
tr("Create Directory"),
tr("Directory name"));
//创建子目录 mkdir(模型索引,目录名)
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; //删除目录 rmdir(模型索引)
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)));
}

转自:http://qimo601.iteye.com/blog/1534325