QDirModel类封装了计算机的文件系统并且可以显示(或者隐藏)不同的文件属性。可以为这个模型应用过滤器,这样就可以根据自己的需要显示不同类型的文件系统条目,并且用不同的方式对这些条目进行排序。
我们先从构造函数开始:
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(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);
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("QDieModel"));
}
构造函数中,首先我们创建了QDirModel的一个对象,并且设置ReadOnly为false,也就是说我们可以对其进行修改。而下一个setSorting()函数是对其进行排序,排序的依据也很清楚:文件夹优先(QDir::DirsFirst),忽略大小写(QDir::IgnoreCase),而且是根据名字排序(QDir::Name)。更多的规则组合可以参见 API 文档了。
然后我们创建一个QTreeView实例,并且把model设置为刚刚的QDirModel实例。然后我们开始设置QTreeView的相关属性。首先把stretchLastSection设置为true。如果把这个属性设置为true,就是说,当QTreeView的宽度大于所有列宽之和时,最后一列的宽度自动扩展以充满最后的边界;否则就让最后一列的宽度保持原始大小。第二个setSortIndicator()函数是设置哪一列进行排序。由于我们前面设置了model是按照名字排序,所以我们这个传递的第一个参数是0,也就是第1列。setSortIndicatorShown()函数设置显示列头上面的排序小箭头。setClickable(true)则允许鼠标点击列头。这样,我们的QTreeView就设置完毕了。最后,我们通过QDir::currentPath()获取当前exe文件运行时路径,并把这个路径当成程序启动时显示的路径。expand()函数即展开这一路径;scrollTo()函数是把视图的视口滚动到这个路径的位置;resizeColumnToContents()是要求把列头适应内容的宽度,也就是不产生...符号。这样,我们就通过一系列的参数设置好了QTreeView,让它能够为我们展示目录结构。
void DirectoryViewer::createDirectory()
{
QModelIndex index = treeView->currentIndex();
if (!index.isValid())
return;
QString dirName = QInputDialog::getText(this, tr("mkdir"), tr("Directory Name:"));
if ( !model->mkdir(index, dirName).isValid() ) {
QMessageBox::information(this, tr("mkidr"),
tr("Failed to create the directory"));
}
}
createDirectory()私有槽调用mkdir()函数来在index处创建一个目录。
void DirectoryViewer::remove()
{
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)));
}
}
remove()私有槽删除当前项对应的文件或者目录。