QString 亂談 3 Qt5與中文

2021-06-06 19:06:49 字數 2379 閱讀 4793

兩個月前,簡單寫過qtextcodec中的setcodecfortr等終於消失了 (qt5) ,在qt論壇上,不少使用者都對去掉這兩個函式表示特別的不了解。為什麼會這樣?我想多少能說明不少使用者對c++中原始碼字符集和執行字符集的不太了解,從而造成對這種函式的依賴或誤用。

今天,隨著change qstring's default codec to be utf-8 進入qt5的master分支,我們總算可以重新審視一下qt的中文支援問題。

20120516更新:建議閱讀qtcore模組維護者thiago macieira 的文章 source code must be utf-8 and qstring wants it 

qstring s1 = "漢語";

qstring s2("漢語");

qstring s3 = tr("中文")

qstring s5 = qstring::fromwchararray(l"中文");

qstring s6 = u8"中文";//c++11

qstring s7 = tr(u8"中文")

...

所有這些在qt5預設都會正常工作,唯一要求就是:確保你的c++的執行字符集(the execution character set)是utf-8

最簡單直接的用法,當屬:

qstring s1 = "漢語";

qstring s2("漢語");

qstring s6 = u8"中文";//c++11

...

這有什麼問題呢?

在qt4中,qobject::tr()是被濫用(誤用)的函式之一:

qstring s3 = tr("中文")

...

原因:

它的用途是用來進行翻譯(i18n和l10n)的,如果你沒有這方面的需求,真的沒必要用它。(在qt4中,我只注意到有2個大陸網友和1個日本網友有需求並真正進行過這方面的嘗試,那麼其他應該算誤用吧?)

剛開始接觸qt和qstring時,曾多次想過,為什麼不用wchar_t,為什麼,...

qstring s5 = qstring::fromwchararray(l"中文");

這個東西在windows下真的很有用:首先它是windows系統api所用字串,其次它和qstring內部表示相同。但是由於msvc處於種種考慮,鼓勵大家使用text/_t,反倒使大家對它比較陌生。

但是從c++標準來說,wchar_t畢竟不是char16_t,所以跨平台性不好。在linux下,這行**需要utf32到utf16的轉換。

這是乙個巨集,乙個蠻複雜的巨集:

qstring s4 = qstringliteral("中文");

在介紹這個巨集之前,我們先看看下面寫法有什麼劣勢:

qstring s1 = "漢語";

qstring s2("漢語");

qstring s3 = tr("中文")

qstring s6 = u8"中文";//c++11

...

首先,2個漢字的字串以utf-8編碼的形式被編譯器放到了常量區。(至少佔7個位元組吧?)

然後,程式執行時,構造qstring例項,需要在堆上申請空間,存放utf16格式的相應字串。

有沒有存在浪費?

qstring 內部是utf16,如果c++編譯器在編譯期直接提供了utf16的字串,那麼我們在qstring內部直接儲存也就夠了。這樣

目前,我們還沒有可靠的方式在c++使用utf16的執行字符集(the execution character set)。

這兩點,導致了qstringliteral的複雜性

原始碼見 qtbase/src/corelib/tools/qstring.h

(**中使用巨集、模板、lambda表示式,還是相當複雜的,此處只摘片段)

#define qt_unicode_literal_ii(str) u"" str

typedef char16_t qunicodechar;

...

#if defined(q_cc_msvc)

# define qt_unicode_literal_ii(str) l##str

#else

# define qt_unicode_literal_ii(str) l"" str

#endif

typedef wchar_t qunicodechar;

...

# define qstringliteral(str) qstring::fromutf8(str, sizeof(str) - 1)

分享到:

QString 亂談 3 Qt5與中文

今天,隨著change qstring s default codec to be utf 8 進入qt5的master分支,我們總算可以重新審視一下qt的中文支援問題。20120516更新 建議閱讀qtcore模組維護者thiago macieira 的文章 source code must be...

qstring亂碼 qt4 QT4 5 1中文亂碼

開始看蔡志明等編寫的 精通qt4程式設計 一書,第乙個例子就出現了問題,例子執行結果如下 其源 為 include include include include include include int main int argc,char ar qtextcodec setcodecfortr q...

Qt中QString與int,char等互轉

a 使用arg long a 36 qstring s qstring 1 arg a s 36 int 轉qsting qstring stepinfo tr time 1 arg qstring number timestamp,10 8,0 10進製,8位,不足補0 b 使用qstring n...