When programming, we often need to use the type of string, there is no doubt that the Qt library is also a string type encapsulation, the QString class provides you can think of all the string manipulation method, to the developer great convenience.
But when we write a program, we inevitably use a third party open Source Library on the Qt framework, because the type of the library is basically the standard type, that is, using char * to represent the string type. So the question is, how do you convert between QString and char *?
The following two scenarios are described.
convert QString to char *
Turn the QString to char *, you need to use the Qbytearray class, the Qbytearray class is described in the Qt Help documentation.
Because char * finally has a ' plus ' as The Terminator, the Qstring::tolatin1 () is followed by the string with ' the '.
The method is as follows:
QString str;
char* ch;
Qbytearray ba = Str.tolatin1 (); Must
Ch=ba.data ();
This completes the conversion of the QString to char *. The bug does not appear when the test program runs. Note that line 3rd, must be added, can not be str.tolatin1 (). Data () is completed in such a step, or there may be an error.
Add: The above method when QString does not contain Chinese, no problem, but QString contains Chinese, convert to char * is garbled, using the following method to solve:
Method 1:
Add GBK Encoding Support:
#include <QTextCodec>
qtextcodec::setcodecfortr (Qtextcodec::codecforname ("GBK"));
Qtextcodec::setcodecforlocale (Qtextcodec::codecforname ("GBK"));
Then modify the 3rd line above to read:
Qbytearray ba = Str.tolocal8bit (); Tolocal8bit Support Chinese
Method 2:
Convert QString to the string type in the standard library, and then convert the string to char *. As follows:
QString filename;
std::string str = filename.tostdstring ();
CONST char* ch = str.c_str ();
Second, char * converted to QString
Converting char * to QString is easier, and we can use the QString constructor to convert:
QString (const qlatin1string &STR);
The Qlatin1string constructor:
qlatin1string (const char *STR);
So using this statement you can convert char * ch to QString str, as follows:
str = QString (qlatin1string (CH));