QString的格式化,我们主要用到的是arg()函数,该函数有很多重载:
QString
arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char(' ')) const
QString
arg(qlonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(qulonglong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(long a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(ulong a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(uint a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(short a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(ushort a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char(' ')) const
QString
arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = QLatin1Char(' ')) const
参数解析:
- fieldWidth 代表限制的字符串宽度
- base 代表进制
- fillChar 代表填充的字符
1、限制字符串宽度,不够则在前面补零
//限制字符串宽度,不够则在前面补零
QString strNumber = QString::number(23);
//十进制数23,字符串宽度:4
QString strConv = QString("%1").arg(strNumber.toInt(), 4, 10, QLatin1Char('0'));
qDebug() << "strConv=" << strConv;//0023
//十进制的23 转为十六进制数,字符串宽度:4
strConv = QString("%1").arg(strNumber.toInt(), 4, 16, QLatin1Char('0'));
qDebug() << "strConv=" << strConv;//0017
//十进制32 转为十六进制,,字符串宽度:0
strConv = QString("%1").arg(32, 0, 16);
qDebug() << "strConv=" << strConv;//20
字符串补零的手动版本:
QString fillWithZero(const QString& src, int length)
{
QString pattern;
for (int i = 0; i < length; i++)
pattern.append("0");
return (pattern + src).right(length);
}
2、保留小数点后几位数
//整数转QString
QString strInt = QString::number(123);
qDebug() << "strInt=" << strInt;
//小数转QString,保留两位小数
QString strDouble = QString::number(123.456789, 'f', 2);
qDebug() << "strDouble=" << strDouble;//123.46
3、时间格式hh:mm:ss
//时间显示格式(12:3:7 > 12:03:07)
QDateTime dt = QDateTime::currentDateTime();
QTime tm = dt.time();
int h = tm.hour();
int m = tm.minute();
int s = tm.second();
QString strTime = QString("%1:%2:%3")
.arg(h, 2, 10, QLatin1Char('0'))
.arg(m, 2, 10, QLatin1Char('0'))
.arg(s, 2, 10, QLatin1Char('0'));
qDebug() << "time=" << strTime;
//asprintf
strTime = QString::asprintf("%02d:%02d:%02d", h, m, s);
qDebug() << "time=" << strTime;