主要是应用QFileSystemModel,和pyqt5的操作差不多
效果图
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle(QStringLiteral("访问本机文件系统"));
model = new QFileSystemModel(this);
model->setRootPath(QDir::currentPath());//设置根目录
ui->treeView->setModel(model);
ui->listView->setModel(model);
ui->tableView->setModel(model);
//信号与槽关联,treeView单击时,其目录设置为listView和tableView的根节点
connect(ui->treeView,SIGNAL(clicked(QModelIndex)),
ui->listView,SLOT(setRootIndex(QModelIndex)));
connect(ui->treeView,SIGNAL(clicked(QModelIndex)),
ui->tableView,SLOT(setRootIndex(QModelIndex)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_treeView_clicked(const QModelIndex &index)
{
ui->checkBox->setChecked(model->isDir(index));//是否是根目录
ui->pathLabel->setText(QStringLiteral("文件目录:")+model->filePath(index));
ui->NameLabel->setText(QStringLiteral("文件名:")+model->fileName(index));
qint64 s = model->size(index);
if(s<1024){
ui->sizeLabel->setText(QStringLiteral("文件大小:")+QString("%1 KB").arg(s));
}else{
ui->sizeLabel->setText(QStringLiteral("文件大小:")+QString("%1 KB").arg(s/1024));
}
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QFileSystemModel>
#include <QString>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_treeView_clicked(const QModelIndex &index);
private:
Ui::MainWindow *ui;
QFileSystemModel *model;
};
#endif // MAINWINDOW_H