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()?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • I later found a related question (but it asks about spaces as well) - https://stackoverflow.com/questions/5209823/how-to-call-qdebug-without-the-appended-spaces-and-newline – sashoalm Feb 20 '15 at 09:31

3 Answers3

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;
sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • 2
    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. – rbaleksandar Sep 06 '16 at 14:10
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.

Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
0

Another way of dealing with your situation.

QString msg;

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

qDebug( "%s, %d", qPrintable( msg ), fontMetricsLeading );
warunanc
  • 2,221
  • 1
  • 23
  • 40