How to print string literal and QString with qDebug?

You can use the following:

qDebug().nospace() << "abc" << qPrintable(s) << "def";

The nospace() is to avoid printing out spaces after every argument (which is default for qDebug()).


No really easy way I am aware of. You can do:

QByteArray s = "value";
qDebug("abc" + s + "def");

or

QString s = "value";
qDebug("abc" + s.toLatin1() + "def");

Option 1: Use qDebug's default mode of a C-string format and variable argument list (like printf):

qDebug("abc%sdef", s.toLatin1().constData());

Option 2: Use the C++ version with overloaded << operator:

#include <QtDebug>
qDebug().nospace() << "abc" << qPrintable(s) << "def";

Reference: https://qt-project.org/doc/qt-5-snapshot/qtglobal.html#qDebug


According to Qt Core 5.6 documentation you should use qUtf8Printable() from <QtGlobal> header to print QString with qDebug.

You should do as follows:

QString s = "some text";
qDebug("%s", qUtf8Printable(s));

or shorter:

QString s = "some text";
qDebug(qUtf8Printable(s));

See:

  • http://doc.qt.io/qt-5/qtglobal.html#qPrintable

  • http://doc.qt.io/qt-5/qtglobal.html#qUtf8Printable