Under QT, strings are used qstring, which is really convenient for developers. QT re-use of third-party open source libraries, because the type of library is basically a standard type, the number of strings encountered is the char* type
QT re-use of third-party open source libraries, because the type of library is basically a standard type, the number of strings encountered is the char* type
Because char* finally has a '/0 ' as the Terminator, and Qstring::tolatin1 () is appended with '/0 ' after the string
Here's how:
1.QString Turn char *
Convert the qstring to Qbytearray first, and then convert the Qbytearray to char *.
Qstring str; char* mm;
Qbytearray tmp = Lineeidt->test (). ToLatin1 ();
Mm=tmp.data ();
This completes the transformation of qstring to char*. A bug does not occur when the test program is running
Note: You cannot use the following conversion form char *mm = str.tolatin1 (). data ();. Because of this, str.tolatin1 () The resulting Qbytearray type results can not be saved, the final conversion, the value of mm is empty.
note the third line, be sure to add, you can not str.tolatin1 (). data () Such a completion may be an error.
Add: The above method when qstring does not contain Chinese, no problem, but qstring contains Chinese, converted to char* is garbled, the following methods to solve:
Method 1:
Add GBK Encoding Support:
#include <QTextCodec>
QTEXTCODEC::SETCODECFORTR (Qtextcodec::codecforname ("GBK")); Qtextcodec::setcodecforlocale (Qtextcodec::codecforname ("GBK"));
Then change the third behavior above: qbytearray ba = Str.toloacl8bit (); Toloacl8bit Support Chinese
Method 2:
Convert the qstring to a string type in the standard library, and then convert the string to char*, as follows:
std::string str = filename.tostdstring ();
CONST char* ch = str.c_str ();
2. Char * Turn qstring
You can use the QString constructor to convert: QString (const qlatin1string &STR);
Qlatin1string constructor: qlatin1string (const char *STR);
The following statement converts char * mm to qstring str:
str = QString (qlatin1string (mm));
Example:
#include <QtGui/QApplication>
#include <QtDebug>
#include <QString>
int main (int argc, char *argv[])
{
Qapplication A (argc, argv);
QString str = "Hello"; qstring Turn char *
Qbytearray ba = Str.tolatin1 ();
Char *mm = Ba.data ();
Qdebug () <<mm<<endl; When debugging, output in console
QString nn = QString (qlatin1string (mm)); char * Turn qstring
Qdebug () <<nn<<endl; When debugging, output in console
return A.exec ();
}
To debug, output the following at the console:
Hello
Hello
/*******************************************
Qstring and Qbytearray provide a very handy operator+ to allow you to write code like this:
QString directory =/*...*/, name =/*...*/;
QString datafile = directory + qlatin1char ('/') + name + qlatin1string (". Dat");
**********************************************/
QT under qstring turn char*