How to get QString qDebug output as string?

1.7k Views Asked by At

Let's have a look at this little application:

#include <QString>
#include <QDebug>

int main(int argc, char *argv[]) {
  const auto test_string = 
    QString{"Some string \n \x01 \u0002 with some \r special chars"};
  qDebug() << test_string;
  qDebug(qPrintable(test_string));
}

It gives the following output:

"Some string \n \u0001 \u0002 with some \r special chars"
Some string
 special chars
Press <RETURN> to close this window...

This demonstrates how the qDebug << operator comes with some functionality that converts all the special characters of a QString to some readable string, which can easily be put in a string declaration in C++.

I would like to use this functionality to feed strings into a custom logging framework. Is there a possibility to use the same conversion function directly?

Effectively, this would mean to convert test_string to a QString instance that gives the same output on both the above qDebug statements.

3

There are 3 best solutions below

0
Christoph Thiede On

I had the same question and I did not found the complete answer (yet). However, I found QVariant which allows you to call toString() on the most basic C and Qt types:

QVariant("foo").toString(); // "foo"
QVariant(true).toString(); // "true"
QVariant(QDateTime("2020-11-28")).toString(); // "2020-11-28"

Then you could wrap this into one method:

QString variantToString(const QVariant variant) {
    return (variant.userType() != QMetaType::QString
            && variant.canConvert(QMetaType::QStringList))
        ? "(" + variant.toStringList().join(", ") + ")"
        : variant.toString();
}

variantToString(42); // "42" // works due to implicit cast

You could do a few extra checks for non-stringifiable types (see also canConvert() and userType(), e.g. lists, regular expressions or whatever you need, but I totally agree that it would be nicer to reuse Qt's own logging functions instead ...

0
asynts On

I had a similar issue but I wanted to use my custom operator<< overload that was defined for QDebug, therefore, I did the following:

// This could be anything that provides an 'operator<<' overload.
QString value = "Hello, world!";

QString result;
QDebug{ &result } << value;
0
BaiJiFeiLong On

One complete example

// Create by [email protected] at 2023-08-11 11:15:13+0800
#include <QtCore/QDebug>
#include <QtCore/QPoint>
#include <QtGui/QColor>
#include <iostream>

template<class T>
std::string qDebugToString(const T &t) {
    QString text;
    QDebug{&text} << t;
    return text.mid(1, text.length() - 2).toStdString();
}

int main() {
    std::cout << "Point: " << qDebugToString(QPoint(1280, 720)) << std::endl;
    std::cout << "Color: " << qDebugToString(QColor("violet")) << std::endl;
    std::cout << "Empty: " << qDebugToString("") << std::endl;
}

The console output

Point: Point(1280,720)
Color: Color(ARGB 1, 0.933333, 0.509804, 0.933333)
Empty: