【发布时间】:2013-08-27 22:38:02
【问题描述】:
有没有简单的方法来完成以下工作?我的意思是Qt 中是否有任何帮助类为qDebug 准备字符串?
QString s = "value";
qDebug("abc" + s + "def");
【问题讨论】:
有没有简单的方法来完成以下工作?我的意思是Qt 中是否有任何帮助类为qDebug 准备字符串?
QString s = "value";
qDebug("abc" + s + "def");
【问题讨论】:
您可以使用以下内容:
qDebug().nospace() << "abc" << qPrintable(s) << "def";
nospace() 是为了避免在每个参数后打印出空格(qDebug() 的默认设置)。
【讨论】:
我知道没有真正简单的方法。你可以这样做:
QByteArray s = "value";
qDebug("abc" + s + "def");
或
QString s = "value";
qDebug("abc" + s.toLatin1() + "def");
【讨论】:
根据Qt Core 5.6 documentation,您应该使用<QtGlobal> 标头中的qUtf8Printable() 打印QString 和qDebug。
你应该这样做:
QString s = "some text";
qDebug("%s", qUtf8Printable(s));
或更短:
QString s = "some text";
qDebug(qUtf8Printable(s));
见:
【讨论】:
qUtf8Printable 和qPrintable 而不是.toLatin1().constData() 和C++ << 运算符。
选项 1:使用 qDebug 的 C 字符串格式和变量参数列表的默认模式(如 printf):
qDebug("abc%sdef", s.toLatin1().constData());
选项 2:使用带有重载 的 C++ 版本
#include <QtDebug>
qDebug().nospace() << "abc" << qPrintable(s) << "def";
参考:https://qt-project.org/doc/qt-5-snapshot/qtglobal.html#qDebug
【讨论】:
只需像这样重写您的代码:
QString s = "value";
qDebug() << "abc" << s << "def";
【讨论】:
我知道这个问题有点老了,但是在网络上搜索它时它几乎出现在最前面。可以重载 qDebug 的运算符(更具体地为 QDebug),使其接受 std::strings,如下所示:
inline QDebug operator<<(QDebug dbg, const std::string& str)
{
dbg.nospace() << QString::fromStdString(str);
return dbg.space();
}
这东西在我所有的项目中存在多年,我几乎忘记了它仍然默认不存在。
在那之后,
【讨论】: