常用基本数据类型互转
1、int 与QString 互转
int-->QString
int tmp = 125;
QString str_a = QString::number(tmp, 10); // str_a == "125" 十进制
QString str_b = QString::number(tmp, 16).toUpper(); // str_b == "7D" 十六进制
QString str_c = QString("%1").arg(tmp, 4, 16, QChar('0'));// str_a == "0125" 十进制
QString str_d = QString("%1").arg(tmp, 4, 16, QChar('0'));// str_b == "007D" 十六进制
QString-->int
QString num = "100";
int int_a = num.toUInt(); //int_a = 100 十进制
int int_b = num.toUInt(16); //int_b = 64 十六进制
2、float 与QString 互转
float-->QString
float tmpNum = 3.1415;
QString str = QString("%1").arg(tmpNum); // str == "3.1415"
QString-->float
QString num = "3.1415" ;
float float_a = num.toFloat(); //float_a = 3.1415
3、char*与QString 互转
QString-->char*
QString qstr = "hello csk";
char * p = qstr.toLocal8Bit().data();
char *pp = qstr.toStdString().data();
string str = qstr.toStdString();
char* ppp = str.c_str();
char*->QString
char* ch = "hello";
qstr = QString(QLatin1String(ch)); // qstr="hello"
4、QString 有string互转
QString-->string
QString qstr = "hello csk";
string stdstr = qstr.toStdString(); //stdstr = "hello csk";
string-->QString
string stdstr = "hello";
QString qstr = QString::fromStdString(str); //qstr = "hello"
5、QString 有QByteArray互转
QByteArray-->QString
QByteArray cstr("abcd");
QString s = cstr;
QByteArray cstr("abcd");
QString s;
s.prepend(cstr);
QString-->QByteArray
QString s("hello");
QByteArray cstr = s.toAscii(); //cstr="hello"
QByteArray cstr1 = s.toLatin1(); //cstr1="hello"
6、QString 转GBK
QString str="你好";
QString::fromLocal8Bit(str.c_str());
QString::fromLocal8Bit("你好");
7、QString 与 wchar_t*互转
QString-->wchar_t*
wchar_t* wptr = L"test";
QString ret = QString::fromWCharArray(wptr); //ret= "test";
QString ret2 = QString((QChar*)wptr, wcslen(wptr)); //ret2= "test";
wchar_t*-->QString
wchar_t szBuf[1024];
QString str = tr("hello");
wcscpy_s(reinterpret_cast<wchar_t*>(szBuf),sizeof(szBuf) / sizeof(wchar_t),reinterpret_cast<const wchar_t*>(str.utf16()));
wchar_t * wptr = reinterpret_cast<const wchar_t *>(str.utf16());
8、QString 与 QDateTime互转
QDateTime-->QString
QString str;
QDateTime time;
time = QDateTime::currentDateTime();
str = time.toString("yyyy-MM-dd hh:mm:ss"); // str = 2018-05-23 17:35:00
QString-->QDateTime
QString strBuffer;
QDateTime time;
strBuffer = "2018-05-23 17:35:00";
time = QDateTime::fromString(strBuffer, "yyyy-MM-dd hh:mm:ss");
9、QString 字体颜色
QString value = "hello,I'm csk";
value = QString("<span style=' color:#ff0000;'>%1</span>").arg(value); //value 的值若显示界面则为红色
10、string 转 wstring
wstring stringTOwstring(const string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
wstring result = _Dest;
delete []_Dest;
return result;
}