【问题标题】:How to print string literal and QString with qDebug?如何使用 qDebug 打印字符串文字和 QString?
【发布时间】:2013-08-27 22:38:02
【问题描述】:

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

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

【问题讨论】:

    标签: c++ qt qstring qdebug


    【解决方案1】:

    您可以使用以下内容:

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

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

    【讨论】:

    • 建议根据文档使用 qUtf8Printable 而不是 qPrintable,因为 qDebug() (和朋友)期望 UTF-8 可能并不总是 toLocal8Bits() (这是 qPrintable 调用的)返回
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      根据Qt Core 5.6 documentation,您应该使用&lt;QtGlobal&gt; 标头中的qUtf8Printable() 打印QStringqDebug

      你应该这样做:

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

      或更短:

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

      见:

      【讨论】:

      • 这确实应该是新接受的答案。我肯定更喜欢使用qUtf8PrintableqPrintable 而不是.toLatin1().constData() 和C++ &lt;&lt; 运算符。
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:

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

        QString s = "value";
        qDebug() << "abc" << s << "def";
        

        【讨论】:

        • 那不一样。您的代码返回 'abc "value" def'。他的代码'abcvaluedef'。不同的用例。
        【解决方案6】:

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

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

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

        在那之后,

        【讨论】:

          猜你喜欢
          • 2017-01-26
          • 2019-05-19
          • 1970-01-01
          • 2017-06-05
          • 1970-01-01
          • 1970-01-01
          • 2015-05-03
          • 2015-12-31
          相关资源
          最近更新 更多