Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

qt - How to deal with "%1" in the argument of QString::arg()?

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

See the Qt docs about QString::arg():

QString str;
str = "%1 %2";
str.arg("%1f", "Hello"); // returns "%1f Hello"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...