user2801678 user2801678 - 3 months ago 18
C++ Question

QString .arg function

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?

Answer

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