34

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");
B Faley
  • 17,120
  • 43
  • 133
  • 223

6 Answers6

25

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

Kurt Pattyn
  • 2,758
  • 2
  • 30
  • 42
  • 2
    It'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 – Daniël Sonck Feb 05 '18 at 23:57
22

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");
Greenflow
  • 3,935
  • 2
  • 17
  • 28
16

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:

Krzysiek
  • 7,895
  • 6
  • 37
  • 38
  • 1
    this should really be the new accepted answer. I would definitely prefer to use `qUtf8Printable` and `qPrintable` over `.toLatin1().constData()` and C++ `<<` operator. – kimbaudi Aug 12 '19 at 12:47
8

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

bleater
  • 5,098
  • 50
  • 48
4

Just rewrite your code like this:

QString s = "value";
qDebug() << "abc" << s << "def";
NG_
  • 6,895
  • 7
  • 45
  • 67
  • 1
    That's not the same. Your code returns 'abc "value" def'. His code 'abcvaluedef'. Different use case. – Greenflow Aug 25 '13 at 09:05
1

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 .

JAV
  • 11
  • 1