ZZ QT under Qstring to char* and Char []

Source: Internet
Author: User

The following content is reproduced: http://www.cnblogs.com/Romi/archive/2012/03/12/2392478.html

-----------------------------------

QT below, strings are used qstring, it does give developers a convenience, think of the VC inside the various variable types defined, and the type of function parameters, often need this year a new type of conversion

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

Under QT How to turn qstring to char*, need to use Qbytearray class, Qbytearray class description see QT Help document.

Because char* finally has a '/0 ' as the Terminator, and Qstring::tolatin1 () is appended with '/0 ' after the string

Here's how:

Qstring str;

char* ch;

Qbytearray ba = Str.tolatin1 ();

Ch=ba.data ();

This completes the transformation of qstring to char*. A bug does not occur when the test program is running

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 ();

--------------------------------------

Currently want to achieve from char[] to qstring between the mutual conversion, the principle should be consistent with the above, but untested, the conclusion is to be verified.

ZZ QT under Qstring to char* and Char []

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.