如何使用 QuaZip 提取 .zip 文件并在 QProgressDialog 中显示其提取进度?
我试过这个 question1 的例子(还有这个 question2 )没有成功。因为我需要解压缩 .zip 文件(不是 .gz 文件)并且该代码显示进度百分比但不解压缩文件。 即便如此,我也不知道如何在 QProgressDialog 中显示 %。
我已经能够使用以下方法提取 .zip 文件:
JlCompress::extractDir("C:/test/test.zip", "C:/test/");
但是,这还不足以实现我的目标,因为我需要在 QProgressDialog 中实时显示提取进度...
这是我的代码:
QString fileName = "C:/test/firefox-29.0.1.gz"; //I need to unzip .zip files
qDebug() << "Opened";
progressUnzip->setWindowTitle(tr("Unzip Manager"));
progressUnzip->setLabelText(tr("Unzipping %1. \nThis can take a long time to complete").arg(fileName));
progressUnzip->setAttribute(Qt::WA_DeleteOnClose);
QFile file(fileName);
file.open(QFile::ReadOnly);
QuaGzipFile gzip;
gzip.open(file.handle(), QuaGzipFile::ReadOnly);
progressUnzip->show();
while(true) {
QByteArray buf = gzip.read(1000);
//process buf
if (buf.isEmpty()) { break; }
QFile temp_file_object;
temp_file_object.open(file.handle(), QFile::ReadOnly);
double progress = 100.0 * temp_file_object.pos() / file.size();
updateUnzipProgress(temp_file_object.pos(), file.size());
qDebug() << qRound(progress) << "%";
}
unzipFinished();
qDebug() << "Finish";
地点:
void MainWindow::updateUnzipProgress(qint64 bytesRead, qint64 totalBytes)
{
qDebug() << bytesRead << "/" << totalBytes;
qint64 th = 1;
if (totalBytes >= 100000000)
{
th = 1000;
}
progressUnzip->setMaximum(totalBytes/th);
progressUnzip->setValue(bytesRead/th);
}
// When unzip finished or canceled, this will be called
void MainWindow::unzipFinished()
{
qDebug() << "Unzip finished.";
progressUnzip->hide();
}
在此代码中,QProgressDialog 不显示任何进度条,最后文件未解压缩。
有什么想法吗?
谢谢你的帮助,
最佳答案
我不会为您编写完整的代码,但我可以给您一些提示来帮助您解决问题。
QuaZIP 库不提供任何有关提取进度的 Qt 信号,这意味着您应该自己实现它。
首先,看一下JlCompress::extractDir
函数实现,看看它是如何工作的。源代码可以找到here .该函数创建一个 QuaZip
对象,它描述了您要提取的 zip 存档。然后它遍历存档中的文件。在每次迭代中,它都会创建一个 QuaZipFile
对象,该对象描述存档中的压缩文件,然后将其数据写入(=提取)到一个新文件中。
这是复制函数:
static bool copyData(QIODevice &inFile, QIODevice &outFile)
{
while (!inFile.atEnd()) {
char buf[4096];
qint64 readLen = inFile.read(buf, 4096);
if (readLen <= 0)
return false;
if (outFile.write(buf, readLen) != readLen)
return false;
}
return true;
}
inFile
是压缩的 (QuaZipFile
) 文件,outFile
是压缩数据提取到的新文件。
现在你应该明白底层逻辑了。
要添加有关提取进度的信号,您可以将 JlCompress::extractDir
源代码复制到某个包装类并进行一些更改。
在遍历存档中的文件时,您可以使用 QuaZipFile::getFileInfo
获取有关它们的信息。该信息包含未压缩的文件大小。现在回到 copyData
函数。您知道写入了多少字节,也知道预期的文件大小。这意味着您可以计算单个文件的提取进度。您还可以使用 QuaZip::getFileInfoList64
获取文件总数及其未压缩的大小。这也可以让您计算整个提取进度。
关于c++ - Qt:QuaZip 提取文件并在 QProgressDialog 中显示其进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136155/