Qt5:如何修改下载速度以显示 1.xx MB/s 而不是 1.xxxxx MB/s

Qt5: how to modify download speed to show 1.xx MB/s instead of 1.xxxxx MB/s?

本文关键字:MB xx xxxxx 显示 何修改 下载速度 修改 Qt5      更新时间:2023-10-16
 ui->progressBar->setTextVisible(true);
 ui->progressBar->setMaximum(totalBytes);
 ui->progressBar->setValue(readBytes);
double speed = readBytes * 1000.0 / downloadTime.elapsed();
    QString unit;
    if (speed < 1024) {
        unit = "bytes/sec";
    } else if (speed < 1024*1024) {
        speed /= 1024;
        unit = "kB/s";
    } else {
        speed /= 1024*1024;
        unit = "MB/s";
    }
    QString spd = QString::number(speed);
    ui->progressBar->setFormat(spd+" "+unit);

它的工作原理是这样的:https://i.stack.imgur.com/86bzs.png

我应该如何修改此代码以显示速度,例如 1.XX MB/s ?感谢您的帮助

你应该使用 QString::number 的第三个参数:

QString::number(1.6183456, 'f', 2)
// -> "1.62"