我遇到 Qt GUI 进度条问题。问题是,对于较大的文件,350MB 及以上...进度条在开始时按预期工作,然后它似乎有一段时间没有移动,然后在工作完成时突然跳到 100%。我不确定为什么会发生这种情况,我想知道是否有一些 Qt 之谜导致了这种情况,或者我是否做错了什么。
#include "aClass.h"
#include <QString>
#include <QTextStream>
#include <QByteArray>
#include <QFile>
const char aClass::BLOCK_MODE_CBC = 1;
aClass::aClass()
{
}
qint64 aClass::doWorkA (const QString fileNameSrc, const QString fileNameDst, byte * a, byte * b, aBitSizeInBytes sizeaBytes, RWBufferSizeInBytes rwBufferSize)
{
QFile infile(fileNameSrc);
QFile outfile(fileNameDst);
if(!infile.open(QIODevice::ReadOnly))
return -1;
if(!outfile.open(QIODevice::WriteOnly))
return -1;
qint64 sizeOfOriginalFileInBytes = infile.size();
//Set range for progress bar
int progressMax = sizeOfOriginalFileInBytes / rwBufferSize;
if(progressMax == 0)
progressMax = 1;
emit setRange(0, progressMax);
byte* readDataBuffer = new byte[rwBufferSize];
byte* writeDataBuffer = new byte[rwBufferSize];
qint64 readSize = 0;
qint64 writeSize = 0;
int progressCounter = 0;
while (!infile.atEnd()) {
readSize = infile.read((char*)readDataBuffer, rwBufferSize);
writeSize = readSize;
something.changeData(writeDataBuffer, readDataBuffer, writeSize);
outfile.write((char*)writeDataBuffer, writeSize);
//Update progress bar value
emit setValue(++progressCounter);
}
delete[] readDataBuffer;
delete[] writeDataBuffer;
infile.close();
outfile.close();
return 0;
}
您正在阻止事件循环
这是基于事件编程的一个经典问题。您需要确保永远不会阻塞事件循环,以保持 GUI 的响应能力。如果您不将主线程的控制权返回给 Qt,那么它就无法更新您的显示。
Qt 的设计理念是主 GUI 线程永远不会长时间保持忙碌状态。您的工作是确保长时间运行的任务不会阻塞事件队列。
解决方案 1:定期归还控制权
这是上面 user763305 的 processEvents 建议。从技术上讲,这是一个权宜之计,因为它只是回避了问题。
解决方案 2:在单独的线程中执行工作
这是更干净的解决方案 - 通过将您的工作拆分到工作线程中,您可以让 GUI 保持对传入事件的响应。 Qt 提供了多种并发执行代码的方法。请参阅下面的链接了解更多信息。
Sources:
- http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/ http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong/
- http://doc.qt.nokia.com/latest/qrunnable.html http://doc.qt.nokia.com/latest/qrunnable.html
- http://doc.qt.nokia.com/latest/qthreadpool.html http://doc.qt.nokia.com/latest/qthreadpool.html
- http://doc.qt.nokia.com/latest/qthread.html http://doc.qt.nokia.com/latest/qthread.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)