复制文件的进度条

Progress bar for copying files

本文关键字:文件 复制      更新时间:2023-10-16

我正在尝试为Qt中的文件副本创建进度条。这是我所能找到的最接近的,但我认为这不起作用,因为根据Qt类文档:

与其他QIODevice实现(如QTcpSocket)不同,QFile不发出aboutToClose()、bytesWritten()或readyRead()信号。此实现细节意味着QFile不适合读取和写入某些类型的文件,例如上的设备文件Unix平台。

我怎么能做这样的事?我不知道如何实现我自己的信号。

这是我的代码:

void Replicator::anotbaandbFile(QDir source, QDir target)
{
    source.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    target.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks);
    qDebug() << "Scanning: " << source.path();
    QStringList sourceFileList = source.entryList();
    QStringList targetFileList = target.entryList();
    for (int aCount = 0; aCount < sourceFileList.count(); aCount++)
    {
        bool found = false;
        for (int bCount = 0; bCount < targetFileList.count(); bCount++)
            if (sourceFileList.at(aCount) == targetFileList.at(bCount))
                found = true;
        if (found == false)
        {
            sourceFile = new QFile(source.absolutePath()+"/"+sourceFileList.at(aCount));
            targetFile = new QFile(target.absolutePath()+"/"+sourceFileList.at(aCount));
            progressBar->setMinimum(0);
            progressBar->setMaximum(sourceFile->size());
            written = 0;
            connect(sourceFile,SIGNAL(bytesWritten(qint64)),SLOT(onWrite(qint64)));
            sourceFile->copy(targetFile->fileName());
            //QFile::copy(source.absolutePath()+"/"+sourceFileList.at(aCount), target.absolutePath()+"/"+sourceFileList.at(aCount));
            qDebug() << source.absolutePath()+"/"+sourceFileList.at(aCount) << " " << target.absolutePath()+"/"+sourceFileList.at(aCount);
        }
    }
}

void Replicator::onWrite(qint64 w)
{
    written += w;
    progressBar->setValue( written );
}

从上述修改的新代码

if (found == false)
        {
            sourceFile = new QFile(source.absolutePath()+"/"+sourceFileList.at(aCount));
            targetFile = new QFile(target.absolutePath()+"/"+sourceFileList.at(aCount));
            progressBar->setMinimum(0);
            progressBar->setMaximum(sourceFile->size());
            QByteArray buffer;
            for (int count = 0; !(buffer = sourceFile->read(1000000)).isEmpty(); count+=1000000)
            {
                targetFile->write(buffer);
                progressBar->setValue(count);
            }
            //targetFile->write(buffer);
            //QFile::copy(source.absolutePath()+"/"+sourceFileList.at(aCount), target.absolutePath()+"/"+sourceFileList.at(aCount));
            qDebug() << "copying " << sourceFile->fileName() << " to " << targetFile->fileName();
        }

您可以简单地按固定大小的部分复制大文件,而不是计算已经复制的部分,并通过将其除以全部部分来计算工作量的百分比。

int iWorkPercentage = (int)(((float)iPortionsProcessed / (float)iOveralPortions) * 100);