本文介绍了如何格式化QString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在ObjC中我会写如下:

In ObjC I would write something like:

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

如何在Qt中执行类似操作?

How to do something like that in Qt?

推荐答案

您可以像这样使用QString.arg

You can use QString.arg like this

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

因为:

更改字符串的位置,而不必更改替换的顺序,例如

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));

正如你所看到的,变化是最小的。当然,你通常不需要关心传递到QString :: arg()的类型,因为大多数类型正确重载。

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()不处理std :: string。你需要在你的std :: string上调用:QString :: fromStdString(),使它成为一个QString,然后传递给QString :: arg()。尝试将使用QString的类与使用std :: string的类分开。

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.

更新:例子由Frank Osterfeld更新。

UPDATE: Examples are updated thanks to Frank Osterfeld.

更新:示例更新感谢alexisdm。

UPDATE: Examples are updated thanks to alexisdm.

这篇关于如何格式化QString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 21:44