《QTreeView+QDirModel实现显示目录结构》:系列教程之二

本文属于《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,即可下载

在这里插入图片描述

 

 

 

 

 

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值