Convert qstring to char * In QT *

Source: Internet
Author: User

In QT, the strings all use qstring, which is indeed convenient for developers. Think about the various variable types defined in VC, and the function parameter types are varied. This year's new type conversion is often required.

When QT uses third-party open-source libraries, the types of libraries are basically standard, and most of the string types are char *.

In QT, how to convert qstring to char * requires the qbytearray class. For details about the qbytearray class, see the QT help document.

Because char * finally has a '/0' as the Terminator, and when qstring: tolatin1 () is used,'/0' is added to the string'

The method is as follows:

Qstring STR;

Char * Ch;

Qbytearray BA = Str. tolatin1 ();

Ch = ba. Data ();

In this way, the conversion from qstring to char * is completed. No bug occurs when the program runs the test.

Note that the third line must be added. It cannot be completed by Str. tolatin1 (). Data (), and an error may occur.

 

Supplement: When qstring does not contain Chinese characters, no problem occurs. However, if qstring contains Chinese characters, conversion to char * is garbled. The following solution is used:

Method 1:

Added 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 supports Chinese

Method 2:

First convert qstring to the string type in the standard library, and then convert string to char *, as shown below:

STD: String STR = filename. tostdstring ();

Const char * Ch = Str. c_str ();

 

Refer:

Http://www.cnblogs.com/Romi/archive/2012/03/12/2392478.html

Http://www.cppblog.com/wicbnu/archive/2011/03/16/141956.aspx

Convert qstring to char * In QT *

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.