简易目录切换-Qt-QFileSystemModel

概要

利用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)); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值