ChatGPT解决这个技术问题 Extra ChatGPT

How to format a QString?

I'd like to format a string for Qt label, I'm programming in C++ on Qt.

In ObjC I would write something like:

NSString *format=[NSString stringWithFormat: ... ];

How to do something like that in Qt?


D
Dat Chu

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.


Avoid .arg().arg() chains like this, instead of .arg( x ).arg( y ).arg( z ) use .arg( x, y, z ). It's both faster and more secure - If string x contains e.g. "%1", y will replace that %1 instead of %2. Usually not what one intended.
Although you can change the ordering, it does not seem possible to remove the numbered arguments. For example, QString("%3").arg("~", "Tom", "Jane") results in "~". Not quite as useful as it seemed at first...
Perhaps, but then it doesn't make sense to leave those extra arguments in arg() as well. In sprintf, if you change the type of the arguments, now you also need to make more changes in your format string.
The 3rd example .arg("~", "Tom", 1) doesn't work, you need replace the numerical argument separately: .arg("~", "Tom").arg(1) or convert it to a string first: .arg("~", "Tom", QString::number(1)).
What about QString("%1 %1 blah blah %1").arg("Tom")?
t
trojanfoe

You can use the sprintf method, however the arg method is preferred as it supports unicode.

QString str;
str.sprintf("%s %d", "string", 213);

l
leyyin

Use QString::arg() for the same effect.