Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print string literal and QString with qDebug?

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");
like image 691
B Faley Avatar asked Aug 25 '13 08:08

B Faley


6 Answers

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

like image 172
Kurt Pattyn Avatar answered Oct 22 '22 14:10

Kurt Pattyn


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");
like image 27
Greenflow Avatar answered Oct 22 '22 15:10

Greenflow


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

like image 15
Krzysiek Avatar answered Oct 22 '22 15:10

Krzysiek


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

like image 8
bleater Avatar answered Oct 22 '22 14:10

bleater


Just rewrite your code like this:

QString s = "value";
qDebug() << "abc" << s << "def";
like image 4
tro Avatar answered Oct 22 '22 15:10

tro


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 .

like image 1
JAV Avatar answered Oct 22 '22 14:10

JAV