32

有没有简单的方法来完成以下工作?我的意思是是否有任何帮助类Qt来准备字符串qDebug

QString s = "value";
qDebug("abc" + s + "def");
4

6 回答 6

24

您可以使用以下内容:

qDebug().nospace() << "abc" << qPrintable(s) << "def";

nospace()是为了避免在每个参数之后打印出空格(这是 的默认值qDebug())。

于 2013-08-25T10:07:57.323 回答
23

我知道没有真正简单的方法。你可以做:

QByteArray s = "value";
qDebug("abc" + s + "def");

或者

QString s = "value";
qDebug("abc" + s.toLatin1() + "def");
于 2013-08-25T08:50:33.367 回答
13

根据Qt Core 5.6 文档,您应该使用qUtf8Printable()from <QtGlobal>header 来打印QString.qDebug

您应该执行以下操作:

QString s = "some text";
qDebug("%s", qUtf8Printable(s));

或更短:

QString s = "some text";
qDebug(qUtf8Printable(s));

看:

于 2016-04-23T22:21:59.887 回答
7

选项 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

于 2014-12-15T07:19:46.273 回答
4

只需像这样重写您的代码:

QString s = "value";
qDebug() << "abc" << s << "def";
于 2013-08-25T08:57:35.880 回答
1

我知道这个问题有点老了,但是在网络上搜索它时它几乎出现在最前面。可以重载 qDebug 的运算符(更具体地为 QDebug)以使其接受 std::strings ,如下所示:

inline QDebug operator<<(QDebug dbg, const std::string& str)
{
    dbg.nospace() << QString::fromStdString(str);
    return dbg.space();
}

这东西在我所有的项目中都存在多年,我几乎忘记了它仍然默认不存在。

在那之后, << 用于 qDebug() 的用法更有用恕我直言。你甚至可以混合使用 QString 和 std::string。一些额外的(但不是真正想要的)功能是,您有时可以输入允许隐式转换为 std::string 的整数或其他类型。

于 2017-06-22T07:19:06.660 回答