#include "mylistview.h" 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))); } }
构造函数中,首先我们创建了QDirModel的一个对象,并且设置ReadOnly为false,也就是说我们可以对其进行修改。而下一个setSorting()函数是对其进行排序,排序的依据也很清楚:文件夹优先(QDir::DirsFirst),忽略大小写(QDir::IgnoreCase),而且是根据名字排序(QDir::Name)。更多的规则组合可以参见 API 文档了。