在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));
}