QT 的编码与解码
qt fromLocal8Bit()函数可以设置编码。
QT默认的编码(unicode)是不能显示中文的,可能由于windows的默认编码的问题,windows默认使用(GBK/GB2312/GB18030),所以需要来更改QT程序的编码来解决中文显示的问题。
系统直接自动将char *的参数转换成为系统默认的编码,然后返回一个QString。
#include <QApplication>
#include <QTextCodec>
#include <QLabel>
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
QString str;
str = str.fromLocal8Bit("Qt中文显示");
hello.setWindowTitle(str);
hello.show();
return app.exec();
}
QString str = "Hello";
In all of the QString functions that takeconst char *parameters, theconst char *is interpreted as a classic C-style '\0'-terminated string encoded in UTF-8.
Converting Between 8-Bit Strings and Unicode Strings
QString provides the following three functions that return a const char * version of the string as QByteArray: toUtf8(),toLatin1(), and toLocal8Bit().
- toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
- toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a superset of US-ASCII (ANSI X3.4-1986) that supports the entire Unicode character set through multibyte sequences.
- toLocal8Bit() returns an 8-bit string using the system's local encoding.
To convert from one of these encodings, QString provides fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other encodings are supported through the QTextCodec class.
As mentioned above, QString provides a lot of functions and operators that make it easy to interoperate with const char *strings. But this functionality is a double-edged sword: It makes QString more convenient to use if all strings are US-ASCII or Latin-1, but there is always the risk that an implicit conversion from or to const char * is done using the wrong 8-bit encoding. To minimize these risks, you can turn off these implicit conversions by defining the following two preprocessor symbols:
QT_NO_CAST_FROM_ASCIIdisables automatic conversions from C string literals and pointers to Unicode.QT_RESTRICTED_CAST_FROM_ASCIIallows automatic conversions from C characters and character arrays, but disables automatic conversions from character pointers to Unicode.QT_NO_CAST_TO_ASCIIdisables automatic conversion from QString to C strings.
One way to define these preprocessor symbols globally for your application is to add the following entry to your qmake project file:
DEFINES += QT_NO_CAST_FROM_ASCII \
QT_NO_CAST_TO_ASCII
You then need to explicitly call fromUtf8(), fromLatin1(), or fromLocal8Bit() to construct a QString from an 8-bit string, or use the lightweight QLatin1String class, for example:
QString url = QLatin1String("http://www.unicode.org/");
Similarly, you must call toLatin1(), toUtf8(), or toLocal8Bit() explicitly to convert the QString to an 8-bit string. (Other encodings are supported through the QTextCodec class.)
浙公网安备 33010602011771号