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

…衆ロ難τιáo~ 提交于 2019-12-12 11:03:11

问题


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


回答1:


You can directly use arg() like this

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

Qt will automatically convert it for you




回答2:


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 "int 5 size_t 6 int 12"
qDebug() << QString("int %1 size_t  %2 int%3").arg(i).arg(ui).arg(j);
// Also outputs "int 5 size_t 6 int 12"
qDebug() << QString("int %1 int %3 size_t %2").arg(i).arg(j).arg(ui);



回答3:


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.



来源:https://stackoverflow.com/questions/8255639/appending-number-to-qstring-with-arg-is-there-better-ways

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!