QTextStream 定点格式化问题

QTextStream fixed point formatting issue

我遇到了 QTextStream 格式问题。我正在使用下面的代码从 quint8 打印一个百分比,它似乎在数字和小数点之间给我一个 space 。例如,我将得到“50%”而不是“50%”,得到“100%”而不是“100%”。

我的问题是什么?

QString retVal;
QTextStream retStream(&retVal);
retStream.setRealNumberNotation(QTextStream::FixedNotation);
retStream.setRealNumberPrecision(0);
retStream << qSetFieldWidth(2)
          << (100*((float)myQuint8)/255.0) << "%";
return retVal;

来自QTextStream::setFieldWidth documentation

Note: The field width applies to every element appended to this stream after this function has been called (e.g., it also pads endl). This behavior is different from similar classes in the STL, where the field width only applies to the next element.

因此您需要在输出“%”字符之前将字段宽度重置为零。