1.QString转string
QString qstr = "test";
string s = qstr.toStdString();
2.string转QString
string s = "test";
QString qstr = QString::fromStdString(s);
3.QString转char *
方法1(推荐):
QString qstr = "test";
char * filename = qstr.toUtf8().data();
方法2:
QString qstr = "test";
char * filename = qst.toLocal8Bit().data();
4.char *转QString
char *ch="test";
QString str(ch); // Qt5
QString str = QString::fromUtf8(ch)); // Qt4
5.QString转const char *
方法1:
QString qstr = "test";
char* filename = qstr .toStdString().c_str();
6.float转string
stringstream ss;
float b = 10.1;
ss << b;
string p;
ss >> p;
cout << p;
注意:如果需要多个float转成string,stringstream的变量ss貌似无法共用,例如下面的例子中只有thresh1能成功输出。thresh2和thresh3是空的。
stringstream ss;
float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
string p1, p2, p3;
ss << thresh1;
ss >> p1; cout << p1;
ss << thresh21;
ss >> p2; cout << p2;
ss << thresh3;
ss >> p3; cout << p3;
如果需要多个float转成string,可以用多个stringstream变量,如下:
stringstream ss1, ss2, ss3;
float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
string p1, p2, p3;
ss1 << thresh1;
ss1 >> p1; cout << p1;
ss2 << thresh21;
ss2 >> p2; cout << p2;
ss3 << thresh3;
ss3 >> p3; cout << p3;
方法2:借助float转QString,再QString转string
7.float转QString
float thresh1 = 10.1, thresh2 = 20.1, thresh3 = 30.1;
QString qstr = QString("%1+%2 %3").arg(thresh1).arg(thresh2).arg(thresh3);