How to print string literal and QString with qDebug?
92,271
Solution 1
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");
Solution 2
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()
).
Solution 3
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:
Solution 4
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
Solution 5
Just rewrite your code like this:
QString s = "value";
qDebug() << "abc" << s << "def";
Author by
B Faley
Updated on March 12, 2020Comments
-
B Faley about 4 years
Is there any easy way to get the following work? I mean is there any helper class in
Qt
which prepares the string forqDebug
?QString s = "value"; qDebug("abc" + s + "def");
-
Greenflow over 10 yearsThat's not the same. Your code returns 'abc "value" def'. His code 'abcvaluedef'. Different use case.
-
Daniël Sonck over 6 yearsIt's recommended to use qUtf8Printable over qPrintable according to the docs, because qDebug() (and friends) expect UTF-8 which may not always be what toLocal8Bits() (which is what qPrintable calls) returns
-
kimbaudi almost 5 yearsthis should really be the new accepted answer. I would definitely prefer to use
qUtf8Printable
andqPrintable
over.toLatin1().constData()
and C++<<
operator.