我有一个QT程序,使用QNetworkAccessManager通过Http POST上传一组文件。所有内容都上传得很好,但是我无法将uploadProgress与进度条连接起来。
这是进行上传的代码:
QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
while (numNetConn > 3) {
qDebug("Waiting for the number of transfers to decrease. [%d]", numNetConn);
QTest::qWait(500);
}
QNetworkReply* reply = networkManager->post(request, multiPart);
multiPart->setParent(reply); // delete the multiPart with the reply
connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
connect(reply, SIGNAL(uploadProgress(qint64, qint64)), SLOT(progressChanged(qint64, qint64)));
void MainWindow::progressChanged(qint64 a, qint64 b) {
if (b > 0) {
qDebug() << "Uploading " << a << "/" << b << "%" << (double)a/(double)b*100.0;
ui->progUpload->setValue((a/b)*100);
qApp->processEvents();
}
}
调试窗口在上传过程中愉快地显示了很多进度,但是当上传到100%时,UI才会在上传结束时更新。
...
Uploading 171606016 / 172918683 % 99.2409
Uploading 171835392 / 172918683 % 99.3735
Uploading 172064768 / 172918683 % 99.5062
Uploading 172294144 / 172918683 % 99.6388
Uploading 172523520 / 172918683 % 99.7715
Uploading 172769280 / 172918683 % 99.9136
Uploading 172918683 / 172918683 % 100
我更新UI的progressChanged()函数中缺少什么?
答案 0 :(得分:5)
您的百分比计算是:
(a/b)*100
此处 a
和b
都是整数类型,因此在a
等于b
之前,a/b
的计算结果为0
。
要获得所需的行为,您可以先进行乘法运算:
100*a/b
您也可以将整数转换为float
或double
(就像在qDebug
语句中一样)。