C++ 将布尔值转换为 QString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9604446/
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-27 13:03:34  来源:igfitidea点击:

Convert bool to QString

c++qt

提问by Jjreina

I want convert bool to QString.

我想将 bool 转换为 QString。

Whats the most efficient way to do it?, This is my code but sure that there is other way better.

最有效的方法是什么?,这是我的代码,但肯定还有其他更好的方法。

bool test = true;
test ? "1" : "0";

Thanks.

谢谢。

回答by tmpearce

You can use the static QString::numbermethod - the bool will be implicitly cast to int to match the integer form of the static factory method, which returns a QStringcontaining 0or 1.

您可以使用静态QString::number方法 - bool 将隐式转换为 int 以匹配静态工厂方法的整数形式,该方法返回一个QString包含01

bool test = true;
QString s = QString::number(test);

回答by Mubin Icyer

qDebug() displays a bool variable as "true" or "false". If you want to get such a string you can change your code a little bit:

qDebug() 将 bool 变量显示为“true”或“false”。如果你想得到这样的字符串,你可以稍微改变你的代码:

bool test = true;
QString boolText = test ? "true" : "false";

回答by Richy

Use QVariant!

使用 QVariant!

From bool to QString:

从 bool 到 QString:

   bool bInput = false;
   QString s = QVariant(bInput).toString();

From QString to bool:

从 QString 到 bool:

  QString s = "true";
  bool bInUse = QVariant(s).toBool();