Avoid newline in qDebug()
Asked Answered
M

3

19

Sometimes I want to output a single line in qDebug(), but with some conditional text, like

if (fontMetricsLeading < 0)
    qDebug() << "!!!";
qDebug() << fontMetricsLeading;

However, that would output them on 2 separate lines.

Is there a way to avoid appending a new line after each qDebug()?

Magee answered 18/11, 2012 at 7:11 Comment(1)
I later found a related question (but it asks about spaces as well) - #5210323Magee
M
35

I just found a solution that seems to work. Reading the docs qDebug() returns a temporary QDebug object, which appends newline on destruction. It seems this temporary object can be stored in a temporary variable:

QDebug debug = qDebug();
if (fontMetricsLeading < 0)
    debug << "!!!";
debug << fontMetricsLeading;
Magee answered 18/11, 2012 at 7:37 Comment(1)
Things are more complicated (unnecessary complicated I might add) in Qt 5.7 (and probably in any 5.x). qDebug() no longer turns a ready-to-use QDebug object hence one has to tackle the whole thing by reading tons of documentation. Quite annoying.Contusion
H
3

You can use the ternary operator.

qDebug() << (fontMetricsLeading < 0 ? "!!!" : "") << fontMetricsLeading;

An alternative would be to build a queue in a QString like this.

QString debugString;

if(fontMetricsLeading < 0)
    debugString += "!!!";

debugString += QString::number(fontMetricsLeading);

qDebug() << debugString;

Although I don't see why you would need to go to this extent if it's just for debug purposes.

Hansen answered 18/11, 2012 at 7:22 Comment(0)
S
0

Another way of dealing with your situation.

QString msg;

if ( fontMetricsLeading < 0 )
{
    msg = "!!!";
}

qDebug( "%s, %d", qPrintable( msg ), fontMetricsLeading );
Swingle answered 18/11, 2012 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.