概要
利用QFileSystemModel与QTreeView组合使用,出现可视化目录查看、切换
QFileSystemModel
本身不提供图形界面,提供相关数据
QTreeView
本身不提供数据,但可提供界面显示
代码实现
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
model = new QFileSystemModel(this);
model->setRootPath("/home/yys/QtProject/目录1");
switchLabel1 = new QPushButton(this);
switchLabel1->setGeometry(200,0,200,50);
switchLabel1->setText("切换目录1/2");
switchLabel = new QPushButton(this);
switchLabel->setGeometry(0,0,200,50);
switchLabel->setText("切换至目录QtProject");
// QString splitter = ".";
tree = new QTreeView(this);
tree->setGeometry(0,50,1024,600);
tree->setModel(model);
tree->setRootIndex(model->index(QDir::currentPath()));
connect(switchLabel,&QPushButton::clicked,this,&MainWindow::onswitchLabel);
connect(switchLabel1,&QPushButton::clicked,this,&MainWindow::onswitchLabel);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onswitchLabel()
{
static int index = 0;
QPushButton *button = dynamic_cast<QPushButton*>(sender());
QString str = "/home/yys/QtProject/目录2";
if(button == switchLabel)
{
str = "/home/yys/QtProject";
}
else
{
switch (index) {
case 0:
index = 1;
str = "/home/yys/QtProject/目录1";
break;
case 1:
index = 0;
str = "/home/yys/QtProject/目录2";
break;
}
}
qDebug() << "enter into:" << str;
model->setRootPath(str);
tree->setRootIndex(model->index(str));
// tree->reset();
}
.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
#include <QFileSystemModel>
#include <QTreeView>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void onswitchLabel();
private:
Ui::MainWindow *ui;
QPushButton *switchLabel = nullptr;
QPushButton *switchLabel1 = nullptr;
QFileSystemModel *model = nullptr;
QTreeView *tree = nullptr;
};
#endif // MAINWINDOW_H
注:
qDebug() << "enter into:" << str;
model->setRootPath(str);//可注释,差异化是,文件夹显示排序会有所变化
tree->setRootIndex(model->index(str));