Qt 基本数据类型转换(int,float,double,datetime,string)

来源:互联网 发布:普通电视怎么连接网络 编辑:程序博客网 时间:2024/04/30 11:56

转发:http://blog.csdn.net/tgzjz/article/details/45074237


在由int, float, double 这样的基本数据类型转换为QString的方法大致如下:

以int为例:

[cpp] view plain copy
  1. int tmp = 125;    
  2. QString str_a = QString::number(tmp, 10);             // str_a == "125"   十进制    
  3. QString str_b = QString::number(tmp, 16).toUpper();   // str_b == "7D"   十六进制  

以float为例,或者:

[cpp] view plain copy
  1. float tmpNum = 3.1415;    
  2. QString str = QString("%1").arg(tmpNum);    // str == "3.1415"  

在工作中,上述转换用的不是很多,大多数都是由QString类型转换到基本的数据类型使用的比较多,由于Qt的API有方法,所以用起来很简单,方法大致如下:

以转为float, double为例:

[cpp] view plain copy
  1. QString str = "3.1415";     
  2. float toFloatValue = str.toFloat();               // toFloatValue == 3.1415    
  3. double toDoubleValue = str.toDouble();     // toDoubleValue == 3.1415  

上面这种方法比较适合与科学计数法的表示:

[cpp] view plain copy
  1. double value = QString("1234.56e-03").toDouble();  // value == 1.23456    

需要注意的是,经常QString的内容转换成对应的基本数据类型是建立在QString的内容正确性的基础上进行的,

假设QString的内容是一个基本数据类型无法识别的情况下会导致转换错误,为了提高程序的健壮性,我们通常会在转换时加一个bool型的变量用于判断转换是否成功,用法如下:

[cpp] view plain copy
  1. QString str = "HelloQt";    
  2. bool ok;    
  3. float value = str.toFloat(&ok);  //如果转换失败时 value == 0.0,  并且ok == false;  

以转int为例:

[cpp] view plain copy
  1. Qstring str = "FF";    
  2. bool ok;    
  3. int dec = str.toInt(&ok, 10);   // dec==255 ; ok==true    
  4. int hex = str.toInt(&ok, 16);   // hex==255;  ok==true;  

转换为QString后就可以进行QString与QDateTime进行转换了,转换的方法如下:

》》 QDateTime 转换为 QString

 函数原型:QString QDateTime::toString ( Qt::DateFormat format = Qt::TextDate ) const

[cpp] view plain copy
  1. QString str;    
  2. QDateTime time;    
  3. time = QDateTime::currentDateTime();    
  4. str = time.toString("yyyy-MM-dd hh:mm:ss");   // strBuffer = 2010-07-02 17:35:00  

》》QString 转换为 QDateTime

 函数原型:QDateTime QDateTime::fromString ( const QString & string, const QString & format )   [static]

[cpp] view plain copy
  1. QString str;    
  2. QDateTime time;    
  3. str = "2010-07-02 17:35:00";    
  4. time = QDateTime::fromString(strBuffer, "yyyy-MM-dd hh:mm:ss");  
0 0