Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 818
sashoalm Avatar asked Nov 18 '12 07:11

sashoalm


2 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;
like image 91
sashoalm Avatar answered Oct 15 '22 10:10

sashoalm


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.

like image 35
Austin Brunkhorst Avatar answered Oct 15 '22 12:10

Austin Brunkhorst