Avoid newline in qDebug()

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

Answers


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;

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.


Another way of dealing with your situation.

QString msg;

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

qDebug( "%s, %d", qPrintable( msg ), fontMetricsLeading );

Need Your Help

Making Tk look like a native Linux app

linux tk

Browsing the TkDocs website, it looks like Tk has come a long way in the "native look and feel" department. But looking at some of these screenshots, it seems to be let down in Linux. If you scroll...

Why do Haskell list comprehensions with multiple generators treat the rightmost generator as the tightest loop?

haskell conventions

I'm reading through the Gentle Introduction and am wondering why in a list comprehension with two generators, the rightmost generator is iterated "the fastest" (i.e. compiles to the innermost loop, I