首页 > 其他分享 >Qt - 实现压缩文件、文件夹和解压缩操作

Qt - 实现压缩文件、文件夹和解压缩操作

时间:2022-11-07 21:58:36浏览次数:54  
标签:Qt res signal 解压缩 压缩文件 CompreDecompreFileThread QString file include

一、前言

        QZipWriter是用来压缩文件的类,需要在安装Qt是选择Sources源码安装。否则,无法使用QZipWriter。

1. QZipWriter详解
1.1 构造方法:

QZipWriter(const QString &fileName, QIODevice::OpenMode mode = (QIODevice::WriteOnly | QIODevice::Truncate) );
QZipWriter(QIODevice *device);

 

 fileName:保存zip文件的地址。

QIODevice 是 QFile 的父类,因此在构造 QZipWriter类的对象时,可以传递一个 QFile 类的对象。

 

1.2 设置压缩权限:

enum CompressionPolicy {
     AlwaysCompress,
     NeverCompress,
     AutoCompress
};
void setCompressionPolicy(CompressionPolicy policy);
CompressionPolicy compressionPolicy() const;


1.3 添加文件:

 void addFile(const QString &fileName, const QByteArray &data);


1.4 添加目录:

void addDirectory(const QString &dirName);


 如果需要将文件压缩到lib目录下,那么可以这样操作:

  writer->addDirectory("lib");
  writer->addFile("lib/" + fileName, const QByteArray &data);


 这样压缩,就可以在压缩包当中看到lib目录,并且文件在lib目录下。

二、实现方式

通过Qt自带的库来实现,使用多线程方式,通过信号和槽来触发压缩与解压缩,并将压缩和解压缩结果回传过来。
使用的类:

#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"

 

三、具体步骤

1、在.pro文件中添加模块gui-private

QT       += core gui gui-private

 

2、通过QObject方式创建多线程实现压缩与解压缩类

CompreDecompreFileThread.h

#ifndef COMPREDECOMPREFILETHREAD_H
#define COMPREDECOMPREFILETHREAD_H

#include <QObject>
#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"
#include <QFileInfoList>
#include <QDir>
#include <QFile>
#include <QThread>
class CompreDecompreFileThread : public QObject
{
    Q_OBJECT
public:
    typedef enum
    {
        success,
        failed,
        running
    }ResultE;
signals:
    void compression_res_signal(ResultE res,quint8 progress,QString remarks = nullptr);
    void decompression_res_signal(ResultE res,quint8 progress,QString remarks = nullptr);
public slots:
    /*
     * 压缩文件
     */
    void compression_file_run(QString srcPath,QString destPath);
    /*
     * 解压文件
     */
    void decompression_file_run(QString srcPath,QString destPath);
public:
    explicit CompreDecompreFileThread(QObject *parent = nullptr);
private:
    /*
     * 遍历压缩文件
     */
    QFileInfoList ergodic_compression_file(QZipWriter *writer,QString rootPath,QString filePath);

private:
    QZipWriter *zipWriter = nullptr;
    QZipReader *zipReader = nullptr;
};

#endif // COMPREDECOMPREFILETHREAD_H

CompreDecompreFileThread.cpp

#include "compredecomprefilethread.h"
#include <QDebug>
#include <QIODevice>

CompreDecompreFileThread::CompreDecompreFileThread(QObject *parent)
    : QObject{parent}
{
    qRegisterMetaType<ResultE>("ResultE");
}

QFileInfoList CompreDecompreFileThread::ergodic_compression_file(QZipWriter *writer, QString rootPath, QString filePath)
{
    QDir dir(filePath);          //遍历各级子目录
    QDir fileDir(filePath);    //遍历子目录中所有文件

    //先遍历文件夹 添加进widget
    QFileInfoList fileList=dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    QFileInfoList folderList = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);   //获取当前所有目录 QDir::Dirs 0x001 列出目录;


    for(int i = 0; i != folderList.size(); i++)         //自动递归添加各目录到上一级目录
    {
        QString namepath = folderList.at(i).absoluteFilePath();    //获取路径
        QFileInfo folderinfo= folderList.at(i);
        QString name=folderinfo.fileName();      //获取目录名


        QStringList list = folderinfo.absoluteFilePath().split(rootPath);
        //qDebug()<<"Dir:"<<folderinfo.absoluteFilePath().remove(list.at(0));
        writer->addDirectory(folderinfo.absoluteFilePath().remove(list.at(0)));

        QFileInfoList child_file_list = ergodic_compression_file(writer,rootPath,namepath);          //进行递归 递归这个文件夹
        fileList.append(child_file_list);
        //  file_list.append(name);

    }
    /*添加path路径文件*/

    fileDir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);        //获取当前所有文件
    fileDir.setSorting(QDir::Name);
    QFileInfoList _fileList = fileDir.entryInfoList();
    for (int i = 0; i < _fileList.size(); ++i) //将当前目录中所有文件添加到treewidget中
    {
        QFileInfo fileInfo = _fileList.at(i);

        QFile file(fileInfo.absoluteFilePath());
        if(file.open(QIODevice::ReadOnly))
        {
            QStringList list = fileInfo.absoluteFilePath().split(rootPath);
            //qDebug()<<"File:"<<fileInfo.absoluteFilePath().remove(list.at(0));
            writer->addFile(fileInfo.absoluteFilePath().remove(list.at(0)),file.readAll());
            file.close();
        }

    }
    return fileList;
}
void CompreDecompreFileThread::compression_file_run(QString srcPath, QString destPath)
{
    qDebug()<<QThread::currentThreadId();
    if(srcPath == nullptr || destPath == nullptr)
    {
        emit compression_res_signal(ResultE::failed,100,tr("路径为空!"));
        return;
    }
    QFileInfo fileDistInfo(destPath);
    if(fileDistInfo.isFile())   //目的路径不能为文件名
    {
        emit compression_res_signal(ResultE::failed,100,tr("路径不能为文件!"));
        return;
    }


    QFileInfo fileInfo(srcPath);
    if(fileInfo.isFile())//压缩的是一个文件
    {
        QString saveFileName = destPath+"/"+fileInfo.baseName()+".zip";
        qDebug()<<"saveFileName:"<<saveFileName;
        this->zipWriter = new QZipWriter(saveFileName);
        QFile file(srcPath);
        if(!file.open(QIODevice::ReadOnly))
        {
            emit compression_res_signal(ResultE::failed,100,tr("文件打开失败!"));
            return;
        }
        emit compression_res_signal(ResultE::running,50,tr("正在压缩中..."));
        this->zipWriter->addFile(file.fileName(),file.readAll());
        this->zipWriter->close();
        delete this->zipWriter;
        this->zipWriter = nullptr;
        emit compression_res_signal(ResultE::running,100,tr("正在压缩中..."));
        emit compression_res_signal(ResultE::success,100,tr("压缩完成!"));
    }
    else    //压缩的是一个文件夹
    {
        QString folderStr = srcPath.mid(srcPath.lastIndexOf("/")).remove("/");
        if(folderStr == nullptr)
        {
            emit compression_res_signal(ResultE::failed,100,tr("压缩文件路径错误!"));
            return;
        }
        emit compression_res_signal(ResultE::running,50,tr("正在压缩中..."));
        QString saveFileName = destPath+"/"+folderStr+".7z";
        qDebug()<<"saveFileName:"<<saveFileName;
        this->zipWriter = new QZipWriter(saveFileName);
        this->zipWriter->addDirectory(folderStr);
        this->ergodic_compression_file(this->zipWriter,folderStr,srcPath);
        delete this->zipWriter;
        this->zipWriter = nullptr;
        emit compression_res_signal(ResultE::running,100,tr("正在压缩中..."));
        emit compression_res_signal(ResultE::success,100,tr("压缩完成!"));
    }

}

void CompreDecompreFileThread::decompression_file_run(QString srcPathAndName, QString destPath)
{
    qDebug()<<QThread::currentThreadId();
    if(srcPathAndName == nullptr || destPath == nullptr)
    {
        emit decompression_res_signal(ResultE::failed,100,tr("路径为空!"));
        return;
    }
    QFileInfo destInfo(destPath);
    if(destInfo.isFile()||!destInfo.exists())
    {
        emit decompression_res_signal(ResultE::failed,100,tr("目的路径异常!"));
        return;
    }

    QFileInfo fileInfo(srcPathAndName);
    if(!fileInfo.isFile() || fileInfo.suffix() !="zip")
    {
        emit decompression_res_signal(ResultE::failed,100,tr("压缩文件为空!"));
        return;
    }
    emit decompression_res_signal(ResultE::running,50,tr("正在解压缩..."));
    this->zipReader = new QZipReader(srcPathAndName);
    bool res = this->zipReader->extractAll(destPath);
    emit decompression_res_signal(ResultE::running,100,tr("正在解压缩..."));
    if(res) //解压缩成功
    {
        emit decompression_res_signal(ResultE::success,100,tr("解压缩完成!"));
    }
    else
    {
         emit decompression_res_signal(ResultE::failed,100,tr("解压缩失败!"));
    }

    this->zipReader->close();
    delete this->zipReader;
    this->zipReader = nullptr;

}

 

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "QtGui/private/qzipreader_p.h"
#include "QtGui/private/qzipwriter_p.h"

#include <QFileInfoList>
#include <QDir>
#include <QFile>

#include "compredecomprefilethread.h"

#include <QThread>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT
signals:
    void compress_signal(QString srcPath,QString destPath);
    void decompress_signal(QString srcPath,QString destPath);
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_btnZip_clicked();

    void on_btnUnZip_clicked();

    void compress_res_slot(CompreDecompreFileThread::ResultE res,quint8 progress,QString remarks = nullptr);
    void decompress_res_slot(CompreDecompreFileThread::ResultE res,quint8 progress,QString remarks = nullptr);

private:
    Ui::MainWindow *ui;
    CompreDecompreFileThread *compreDecompreFileThread;
    QThread *compreDecompreFileMainThread;

};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    compreDecompreFileThread = new CompreDecompreFileThread;
    compreDecompreFileMainThread = new QThread;

    compreDecompreFileThread->moveToThread(compreDecompreFileMainThread);
    compreDecompreFileMainThread->start();

    connect(this,&MainWindow::compress_signal,compreDecompreFileThread,&CompreDecompreFileThread::compression_file_run);
    connect(this,&MainWindow::decompress_signal,compreDecompreFileThread,&CompreDecompreFileThread::decompression_file_run);

    connect(compreDecompreFileThread,&CompreDecompreFileThread::compression_res_signal,this,&MainWindow::compress_res_slot);
    connect(compreDecompreFileThread,&CompreDecompreFileThread::decompression_res_signal,this,&MainWindow::decompress_res_slot);
    qDebug()<<QThread::currentThreadId();
}

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


//bool zipReader(QString zipPath="test.zip", QString zipDir="")
//{
//    QDir tempDir;
//    if(!tempDir.exists(zipDir)) tempDir.mkpath(zipDir);
//    QZipReader reader(zipPath);
//    return reader.extractAll(zipDir);
//}

void MainWindow::on_btnZip_clicked()
{
    QString filePath = QApplication::applicationDirPath()+"/test";
    QString zipPath = QApplication::applicationDirPath();

    emit compress_signal(filePath,zipPath);

}


void MainWindow::on_btnUnZip_clicked()
{
    QString filePath = QApplication::applicationDirPath()+"/test.zip";
    QString zipPath = QApplication::applicationDirPath()+"/unTest";

    qDebug()<<"filePath:"<<filePath<<"zipPath:"<<zipPath;

    emit decompress_signal(filePath,zipPath);
}

void MainWindow::compress_res_slot(CompreDecompreFileThread::ResultE res, quint8 progress, QString remarks)
{
    qDebug()<<"Com:"<<"  res:"<<res<<"  progress:"<<progress<<"  remarks:"<<remarks;
}

void MainWindow::decompress_res_slot(CompreDecompreFileThread::ResultE res, quint8 progress, QString remarks)
{
    qDebug()<<"deCom:"<<"  res:"<<res<<"  progress:"<<progress<<"  remarks:"<<remarks;
}

mainwindow.ui


————————————————
版权声明:本文为CSDN博主「小灰灰搞电子」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_15181569/article/details/125159777

标签:Qt,res,signal,解压缩,压缩文件,CompreDecompreFileThread,QString,file,include
From: https://www.cnblogs.com/zhuchunlin/p/16867595.html

相关文章

  • v1.9.0 进行中:开箱即用的 MQTT bench 工具
    十月初,MQTTX团队发布了1.8.3版本。对桌面端应用实现了MQTT5.0版本适配,MQTTXCLI支持了多主题订阅,同时修复了多个已知问题。此外,团队正专注于1.9.0版本的开发,最主......
  • (vs + qt )c++ 调用 python 问题处理
    问题1.PyImport_ImportModule返回总是nullPyObject*pModule=PyImport_ImportModule("test2");//如果加载失败,则返回 if(!pModule){ std::cout<<"WhyCan'top......
  • PyQt5中处理自定义槽的手段(对于界面继承的封装)
    自定义槽由于我打算用QT编辑器来设计Qt界面,所以少不了ui转py的这一步骤。但是每次转ui时,都会自动覆盖原来的文件,这样的话,如果需要在源文件的基础上添加自定义槽,就很麻烦......
  • build opencv with qt to make debugging easier
    最近发现使用自己编译的opencv,可以增强opencv的imshow函数功能。从哪里得到的线索已经忘记了。可能是无意中发现的某一张截图吧。要实现cv::imshow函数功能增强,需要在cmak......
  • Qt视频播放01-共享解码线程(耗时一年/性能凶残/至臻完美)
    一、前言大概在8年前就开始用ffmpeg做视频解码的显示,第一个版本就100行代码左右,功能极其简单,就是开个线程解码视频流转成图片发给主界面绘制。时间过得真快,从当初的一胎到......
  • 用 VS Code 搞 Qt6:让信号和槽自动建立连接
    Qt具备让某个对象的信号与符合要求的槽函数自动建立连接。弄起来也很简单,只要调用这个静态方法即可:QMetaObject::connectSlotsByName(...);connectSlotsByName方法需......
  • Openssl Des3对压缩文件进行加密命令详解
    群友提问:致力于明天:tar-cvf-WMG_Back_"$Today"|openssldes3-salt-khY91gd3GJAAfghECleLwWQAPGK9Cxs-out$dir_backup_today.tar.des3致力于明天:有人懂这个......
  • Qt获取文件存储路径,绝对路径与相对路径,斜杠与反斜杠转换
     Qt获取文件存储路径QStringdirPath=QFileDialog::getExistingDirectory(this,tr("浏览选择文件夹"),tr("C:"));//返回用户选择的路径if(dirPath.isEmpty())//......
  • Esp32 Mqtt
    使用esp32连接MQTT服务器使用Arduino库PubSubClient.h修改PubSubClient.h文件基本初始化引入头文件#include"PubSubClient.h"constchar*ssid="XXXX";......
  • Qtui界面2k显示器显示不全的问题
    做项目时,运行qt生成界面控件字体显示不全,参考下面的博客解决。参考:Qt5.9界面设计中控件的文字显示不完全解决方案_冰蓝樱草的博客-CSDN博还找到一个博客,里面设置字体增大......