【问题标题】:QString .arg functionQString .arg 函数
【发布时间】:2013-12-20 18:49:06
【问题描述】:

我目前正在使用 QT 中的 QStrings,似乎无法理解为什么以下代码不适合我。

#include <QCoreApplication>
#include <QDebug>
#include <QString>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString test;

    int x = 5;

    test.append("This is a test of the Arg Function %1").arg(x);
    qDebug() << test;
    //should output This is a test of the Arg Function 5
    return a.exec();
}

我得到的输出是:

这是对 Arg 函数 %1 的测试

显然我期望值 5 来代替 %1,我在这里遗漏了一些明显的东西吗?

【问题讨论】:

  • 我觉得应该是:test.append(QString("This is a test of the Arg Function %1").arg(x));
  • 编译器没有警告你test.append("This is a test of the Arg Function %1").arg(x);

标签: c++ qt qstring


【解决方案1】:

您需要test = test.append("This is a test of the Arg Function %1").arg(x);,因为arg 返回新字符串。

来自here的示例:

QString i;           // current file's number
QString total;       // number of files to process
QString fileName;    // current file's name

QString status = QString("Processing file %1 of %2: %3")
                .arg(i).arg(total).arg(fileName);

或者喜欢vahancho 建议:

test.append(QString("This is a test of the Arg Function %1").arg(x));

Michael Burr 建议:

test += QString("This is a test of the Arg Function %1").arg(x);

另一个没有arg

test.sprintf("This is a test of the Arg Function %d", x);

你可以看看那个人How to format a QString?

【讨论】:

  • test += QString("This is a test of the Arg Function %1").arg(x);
【解决方案2】:

因为您不阅读有关 QString::arg 的文档。它返回字符串的副本。

qDebug() << test.arg(x) - it`s must work

【讨论】:

    猜你喜欢
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 2016-06-01
    • 2011-07-12
    • 2012-09-27
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多