What is the difference between QString and QLatin1String?

Like the name

1. What is the difference between QString and QLatin1String ??

2.when and where do I need to use one of them?

3.following:

QString str; str = ""; str = QLatin1String(""); 

Is "" == QLatin1String("") ??

+7
source share
2 answers

QString contains unicode. The string literal "foo" is a sequence of bytes that can contain text in any encoding. When you assign a string literal to a QString, QString str = "foo" you implicitly convert from a byte sequence to an undefined encoding in QString, where unicode is located. The QString constructor (const char *) assumes ASCII and is converted as if you typed QString str = QString::fromAscii("foo") . This will break if you use non-ascii literals in your source files (e.g. japanese string literals in UTF-8) or transfer personal data from char * or QByteArray that you read from other sources (file, socket, etc. ), Thus, it is good practice to preserve the QString Unicode world and QByteArray / char * byte array, and only convert between the two explicitly, clearly indicating which encoding you want to use to convert between the two. You can specify QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to force the conversion of explicit conversions (I will always include them when writing any parser). Now, to assign the string literal latin1 to the QString variable using an explicit conversion, you can use

 QString foo = QString::fromLatin1("fรถรถ"); 

or

 QString foo = QLatin1String("fรถรถ"); 

Both claim that the literal is encoded in latin1 and allows encoding-safe conversion to unicode. I find QLatin1String more pleasant to read, and QLatin1String docs explains why in some situations it will be faster.

Combining string literals or, in some cases, QByteArray or char * variables containing latin1 data for conversion are the main uses for QLatin1String, you cannot use QLatin1String as arguments to a method, member variables, or time series (all QString).

+11
source

QString is based on Unicode, and QLatin1String is based on US-ASCII / Latin-1

Unicode is a super-set of US-ASCII / Latin-1. If you are dealing only with US-ASCII / Latin-1 characters, then they are the same for you.

http://doc.qt.io/qt-4.8/qstring.html

http://doc.qt.io/qt-4.8/qlatin1string.html

0
source

All Articles