如何格式化 QString?
我想格式化 Qt 标签的字符串,我在 Qt 上用 C++ 编程。
在 ObjC 中我会写这样的内容:
NSString *format=[NSString stringWithFormat: ... ];
How to do things like that in Qt?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以像这样使用 QString.arg
该方法优于 sprintf,因为:
更改字符串的位置而不必更改替换顺序,例如
或者,更改参数的类型不需要更改格式字符串,例如
如您所见,变化很小。当然,您通常不需要关心传递给 QString::arg() 的类型,因为大多数类型都已正确重载。
但有一个缺点:QString::arg() 不处理 std::string。在将 std::string 传递给 QString::arg() 之前,您需要调用: QString::fromStdString() 将其转换为 QString。尝试将使用 QString 的类与使用 std::string 的类分开。或者如果可以的话,完全切换到 QString。
更新:示例由 Frank Osterfeld 更新。
更新:感谢 alexisdm 更新了示例。
You can use QString.arg like this
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
Or, changing the type of the arguments doesn't require changing the format string, e.g.
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.
您可以使用 sprintf 方法,但首选 arg 方法,因为它支持 unicode。
You can use the
sprintf
method, however thearg
method is preferred as it supports unicode.使用
QString::arg()
一样的效果。Use
QString::arg()
for the same effect.