How to print string literal and QString with qDebug?

109.6k views Asked by At

Is there any easy way to get the following work? I mean is there any helper class in Qt which prepares the string for qDebug?

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

There are 6 answers

0
Greenflow On BEST ANSWER

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");
1
NG_ On

Just rewrite your code like this:

QString s = "value";
qDebug() << "abc" << s << "def";
0
bleater On

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

1
Kurt Pattyn On

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

1
Krzysiek On

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:

0
JAV On

I know this question is a bit old, but it appears nearly on top when searching for it in the web. One can overload the operator for qDebug (more specific for QDebug) to make it accept std::strings like this:

inline QDebug operator<<(QDebug dbg, const std::string& str)
{
    dbg.nospace() << QString::fromStdString(str);
    return dbg.space();
}

This thing is for years in all of my projects, I nearly forget it is still not there by default.

After that, usage of << for qDebug() is a lot more usable imho. You can even mix QString and std::string. Some additional(but not really intended) feature is, that you sometimes can throw in integers or other types that allow implicit conversion to std::string .