C++ 如何格式化 QString?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4784155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:28:42  来源:igfitidea点击:

How to format a QString?

c++qtstring-formatting

提问by hubert poduszczak

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

我想为 Qt 标签格式化一个字符串,我在 Qt 上用 C++ 编程。

In ObjC I would write something like:

在 ObjC 中,我会写一些类似的东西:

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

How to do something like that in Qt?

如何在 Qt 中做类似的事情?

回答by Dat Chu

You can use QString.arg like this

你可以像这样使用 QString.arg

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

This method is preferred over sprintf because:

这种方法比 sprintf 更受欢迎,因为:

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.

如您所见,变化很小。当然,您通常不需要关心传递给 QString::arg() 的类型,因为大多数类型都已正确重载。

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.

但有一个缺点:QString::arg() 不处理 std::string。在将它传递给 QString::arg() 之前,您需要在 std::string 上调用: QString::fromStdString() 以使其成为 QString。尝试将使用 QString 的类与使用 std::string 的类分开。或者,如果可以,完全切换到 QString。

UPDATE: Examples are updated thanks to Frank Osterfeld.

更新:感谢 Frank Osterfeld 更新了示例。

UPDATE: Examples are updated thanks to alexisdm.

更新:感谢 alexisdm 更新了示例。

回答by trojanfoe

You can use the sprintfmethod, however the argmethod is preferred as it supports unicode.

您可以使用该sprintf方法,但arg首选该方法,因为它支持 unicode。

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

回答by Stephen Chu

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

使用QString::arg()相同的效果。