简单的文件对话框-QT5


在QTreeView中设置Model为QFileSystemModel,可以显示文件树,在QListView中设置Model为QFileSystemModel可以显示文件夹下文件列表。

#ifndef QFILESYSTEMMODELDIALOG_H
#define QFILESYSTEMMODELDIALOG_H

#include <QDialog>
#include <QFileSystemModel>

namespace Ui {
class QFileSystemModelDialog;
}

class QFileSystemModelDialog : public QDialog
{
    Q_OBJECT
    
public:
    explicit QFileSystemModelDialog(QWidget *parent = 0);
    ~QFileSystemModelDialog();
    
private slots:
    void on_treeView_clicked(const QModelIndex &index;);

private:
    Ui::QFileSystemModelDialog *ui;

    // Make two models instead of one
    // to filter them separately
    QFileSystemModel *dirModel;
    QFileSystemModel *fileModel;
};

#endif // QFILESYSTEMMODELDIALOG_H
#include "qfilesystemmodeldialog.h"
#include "ui_qfilesystemmodeldialog.h"

QFileSystemModelDialog::QFileSystemModelDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QFileSystemModelDialog)
{
    ui->setupUi(this);

    // Creates our new model and populate
    QString mPath = "C:/";

    // DIRECTORIES

    dirModel = new QFileSystemModel(this);

    // Set filter
    dirModel->setFilter(QDir::NoDotAndDotDot |
                        QDir::AllDirs);

    // QFileSystemModel requires root path
    dirModel->setRootPath(mPath);

    // Attach the dir model to the view
    ui->treeView->setModel(dirModel);


    // FILES

    fileModel = new QFileSystemModel(this);

    // Set filter
    fileModel->setFilter(QDir::NoDotAndDotDot |
                        QDir::Files);

    // QFileSystemModel requires root path
    fileModel->setRootPath(mPath);

    // Attach the file model to the view
    ui->listView->setModel(fileModel);
}

QFileSystemModelDialog::~QFileSystemModelDialog()
{
    delete ui;
}

void QFileSystemModelDialog::on_treeView_clicked(const QModelIndex &index;)
{
    // TreeView clicked
    // 1. We need to extract path
    // 2. Set that path into our ListView

    // Get the full path of the item that's user clicked on
    QString mPath = dirModel->fileInfo(index).absoluteFilePath();
    ui->listView->setRootIndex(fileModel->setRootPath(mPath));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值