Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QString::arg() with number after placeholder

Tags:

qt

qstring

I want to use .arg() on a string. This is an example:

qDebug() << QString("%11%2").arg(66).arg(77);

I would like to get the output 66177 but of course this isn't the actual output since %11 is interpreted as placeholder #11 instead of place holder #1 followed by a literal 1.

Is there a better solution than the following?

qDebug() << QString("%1%2%3").arg(66).arg(1).arg(77);
like image 624
Silicomancer Avatar asked Feb 19 '16 23:02

Silicomancer


2 Answers

The arg replaces sequence with lowest value after %. Range must be betwen 1 and 99. So you dont have to use 1 index you can use two digit number instead one digit number.

Try this and see what will happen:

qDebug() << QString("%111%22").arg(66).arg(77);

This should give you expected result (I've test it on qt 5.4 and it works perfectly).

I've also tested solution form comment under the question and it works to:

qDebug() << QString("%011%02").arg(66).arg(77);
like image 105
Marek R Avatar answered Oct 10 '22 11:10

Marek R


The sense of arg() is that it is replacing everything from %1 to %99 that is why you should not have %11. There are several ways to escape this.

Your way is fine as well as you can have 1 as constant earlier in your code:

qDebug() << QString("%1%2%3").arg(66).arg(1).arg(77);

Or you can have:

qDebug() << QString("%1").arg(66) + "1" + QString("%1").arg(77);

Using QString::number is ok too as was specified in comment.

like image 33
demonplus Avatar answered Oct 10 '22 12:10

demonplus