Question

I am currently playing around with QStrings in QT and can't seem to understand why the following code is not working for me.

#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();
}

The output I am getting is:

This is a test of the Arg Function %1

Obviously I am expecting the value 5 to replace the %1, am I missing something obvious here?

Was it helpful?

Solution

You need to test = test.append("This is a test of the Arg Function %1").arg(x); because arg returns new string.

Example from 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);

Or like vahancho suggested:

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

Michael Burr suggested:

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

Another one without arg:

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

And you may have a look at that guy How to format a QString?

OTHER TIPS

Because you don`t read documentation on QString::arg. It returns copy of the string.

qDebug() << test.arg(x) - it`s must work
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top