让我们看看这个小应用程序:
#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));
}
它给出以下输出:
"Some string \n \u0001 \u0002 with some \r special chars"
Some string
special chars
Press <RETURN> to close this window...
这演示了 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++.
我想使用此功能将字符串输入自定义日志框架。是否可以直接使用相同的转换函数?
实际上,这意味着将 test_string 转换为 QString 实例,该实例在上述两个 qDebug 语句上提供相同的输出。
QVariant
允许你在最基本的 C 和 Qt 类型上调用 toString()
:
QVariant("foo").toString(); // "foo"
QVariant(true).toString(); // "true"
QVariant(QDateTime("2020-11-28")).toString(); // "2020-11-28"
然后你可以将其包装到一个方法中:
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
canConvert()
和 userType()
,例如列表、正则表达式或任何您需要的内容,但我完全同意重用 Qt 会更好而是使用自己的日志记录功能...
我有类似的问题,但我想使用为
operator<<
定义的自定义 QDebug
重载,因此,我执行了以下操作:
// 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: