如何在 QT 中使用 DEBUG 对齐日志文件中的数据?

How to align data in log file using DEBUG in QT?

我想在我的 QT 应用程序的日志文件中显示数据。为此,我使用 DEBUG().

我显示的数据是:

Time since beginning of the test (ms) :  751  Pressure :  "0.051547" 
Time since beginning of the test (ms) :  2498  Pressure :  "0.116169" 
Time since beginning of the test (ms) :  8498  Pressure :  "0.253792" 
Time since beginning of the test (ms) :  10497  Pressure :  "0.290243" 
Time since beginning of the test (ms) :  12597  Pressure :  "0.316798"

但我想像对齐列一样对齐变量。 我想要这样的东西:

Time since beginning of the test (ms) :    751  Pressure :  "0.051547" 
Time since beginning of the test (ms) :   2498  Pressure :  "0.116169" 
Time since beginning of the test (ms) :   8498  Pressure :  "0.253792" 
Time since beginning of the test (ms) :  10497  Pressure :  "0.290243" 
Time since beginning of the test (ms) :  12597  Pressure :  "0.316798"

我使用的代码是:

for (int i = 0 ; i < _pressureValues.length() ; i++)
{
    DEBUG() << "Time since beginning of the test (ms) : " << _pressureValues[i].first
            << " Pressure : " << _pressureValues[i].second;
}

有没有函数可以指定在一定位数上显示一个变量?

您不能直接使用 DEBUG() 执行此操作 - 您需要事先格式化输出字符串。 QString 有例如QString QString::arg(double a, int fieldWidth = 0, char format = 'g', int precision = -1, QChar fillChar = QLatin1Char(' ')) 函数允许您格式化数字。

for (int i = 0 ; i < _pressureValues.length() ; i++)
{
    const QString firstPressureValue = QString("%1").arg(_pressureValues[i].first, 5);
    DEBUG() << "Time since beginning of the test (ms) : " << firstPressureValue 
        << " Pressure : " << _pressureValues[i].second;
}

尽管首先将整个内容包装在 QString 中可能是明智的:

QString debugString = QString("Time since beginning of the test (ms) : %1 Pressure : %2");
QString firstPressureValue = QString("%1").arg(_pressureValues[i].first, 5);
DEBUG() << debugString.arg(firstPressureValue, QString::number(_pressureValues[i].second));