Appending number to QString with arg() , is there better ways?
Asked Answered
P

3

8

I've been using QString::number () to convert numbers to string for long time , now i'm wondering if there's something better than following:

  int i = 0;
  QString msg = QString ("Loading %1").arg (QString::number (i));

How can i spare QString::number () ? i checked document , seems only "%1" is applicable , no other stuff like "%d" could work

Phasia answered 24/11, 2011 at 10:35 Comment(3)
What is the motivation? To save typing or something else?Tripalmitin
@Tripalmitin , yeah , sort of , and i'm thinking if printf like format string is possiblePhasia
@Tripalmitin , %1 seems pretty generalPhasia
C
10

You can directly use arg() like this

int i = 0;
QString msg = QString ("Loading %1").arg(i);

Qt will automatically convert it for you

Carraway answered 24/11, 2011 at 10:43 Comment(0)
E
14

QString's arg() function does indeed implement many different types and automatically detect what you provide it. Providing multiple parameters to a single arg() call like so

// Outputs "one two three"
QString s = QString("%1 %2 %3").arg("one", "two", "three")

is only implemented for QString (and hence const char*) parameters.

However, you can chain arg calls together and still use the numbering system:

int i = 5;
size_t ui = 6;
int j = 12;
// Outputs "i: 5, ui: 6, j: 12"
qDebug() << QString("i: %1, ui: %2, j: %3").arg(i).arg(ui).arg(j);
// Also outputs "i: 5, ui: 6, j: 12"
qDebug() << QString("i: %1, ui: %3, j: %2").arg(i).arg(j).arg(ui);

UPDATE

Qt 5.14 introduced a variadic templated form of arg which should allow multiple non-string args to a single call:

template <typename Args> QString QString::arg(Args &&... args) const

Args can consist of anything that implicitly converts to QString, QStringView or QLatin1String.

Epner answered 2/7, 2013 at 15:15 Comment(0)
C
10

You can directly use arg() like this

int i = 0;
QString msg = QString ("Loading %1").arg(i);

Qt will automatically convert it for you

Carraway answered 24/11, 2011 at 10:43 Comment(0)
G
0

Take a look at QString documentation. You have plenty of ::arg method overloads, that take different types. QString doesn't need to know what type will be under %n, method replacing that %n will know it and put proper value.

Gauche answered 24/11, 2011 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.