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.
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;
// 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;
}
Point: Point(1280,720)
Color: Color(ARGB 1, 0.933333, 0.509804, 0.933333)
Empty:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With