本文属于《QTreeView使用系列教程》之一,欢迎查看其它文章。
1、QDirModel的使用
Qt上可以使用QFileSystemModel和QDirModel都可以获得文件系统目录结构数据。这里以QDirModel为例进行说明。
QDirModel类为本地文件系统提供了一个数据模型,显示我们采用QTreeView。
按照系列教程(一)中对原理的讲解,只要具备model和view,那么就可以进行显示了。
核心代码就三句话:
model = new QDirModel;
treeView = new QTreeView;
treeView->setModel(model);
创建一个model和view,再把model设置到view里面,view就可以显示数据了。是不是很简单。
其他的一些添油加醋的代码,无非就是些按钮,view默认展开哪个目录。
DirectoryViewer.cpp:
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);
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("Directory Viewer"));
}
结果:
2、此文存在的意义
并不是为了讲解QDirModel的使用。而是为了为后续讲解自定义model作铺垫。QDirModel属于Qt自带的model,通过先了解model的用法,以及数据如何存取。
然后再学习自定义model,自定义model用法和QDirModel是一样的。只不过QDirModel提供了文件系统标准的数据,所以Qt给提供为标准模块了。
而我们自定义model数据样式繁多,所以需要我们自己实现。
若对你有帮助,欢迎点赞、收藏、评论,你的支持就是我的最大动力!!!
同时,阿超为大家准备了丰富的学习资料,欢迎关注公众号“超哥学编程”,即可领取。
本文涉及工程代码,公众号回复:33DirectoryViewer,即可下载。