Everybody loves
QString("Put something here %1 and here %2")
.arg(replacement1)
.arg(replacement2);
but things get itchy as soon as you have the faintest chance that replacement1
actually contains %1
or even %2
anywhere. Then, the second QString::arg()
will replace only the re-introduced %1
or both %2
occurrences. Anyway, you won't get the literal "%1"
that you probably intended.
Is there any standard trick to overcome this?
If you need an example to play with, take this
#include <QCoreApplication>
#include <QDebug>
int main()
{
qDebug() << QString("%1-%2").arg("%1").arg("foo");
return 0;
}
This will output
"foo-%2"
instead of
"%1-foo"
as might be expected (not).
qDebug() << QString("%1-%2").arg("%2").arg("foo");
gives
"foo-foo"
and
qDebug() << QString("%1-%2").arg("%3").arg("foo");
gives
"%3-foo"
operator + ()
but in some places, e.g. translation usingtr()
, one would like to keep the ability to reorder the arguments in the template. – Michal%1
to replace the "where" and%2
to replace "what" - now in some cases you simply replace "where" with a string, in others you'd like a number. In case of the string you'd maybe want to put apostrophes around it, in case of a number a hashtag in front would be good to improve readability. Now you can use the 1st arg-call to replace%1
with f.e."#%3"
and a 3rd arg-call to insert the number. – Dangle