在國際化的進行中,如果使用 qt widgets 自帶的原生功能,其中很多文本并不會被自行翻譯,例如:qtextedit 右鍵菜單(複制、粘貼)。
最好的方式是 qt 能提供相關子產品的 ts 翻譯源,開發者根據所要翻譯的内容自行翻譯。但是,查找 qt 安裝目錄,并沒有相關的的翻譯源。既然這樣,那我們隻能自行解決了!
<a href="#%e7%ae%80%e8%bf%b0">簡述</a>
<a href="#%e6%b7%bb%e5%8a%a0%e7%bf%bb%e8%af%91%e6%ba%90">添加翻譯源</a>
<a href="#%e6%8f%90%e5%8f%96%e7%bf%bb%e8%af%91%e6%ba%90">提取翻譯源</a>
<a href="#%e5%8f%91%e5%b8%83">釋出</a>
<a href="#%e5%8a%a0%e8%bd%bd%e7%bf%bb%e8%af%91%e6%96%87%e4%bb%b6">加載翻譯檔案</a>
qt 部件相關的子產品為 widgets,由于需要翻譯的文本屬于 widgets 的源碼,進入 widgets 源碼相關路徑(例如,d:\qt\qt5.7.0\5.7\src\qtbase\src\widgets),打開 widgets.pro,添加:
注意:名字可以随意取 - 由于翻譯的内容屬于 widgets 子產品,為了見名知義,是以起名為 widgets.ts。
要提取翻譯源 widgets.ts,可以通過下面兩種方式:
使用指令行,lupdate widgets.pro
在 qt creator 的系統菜單中,選擇:工具 -> 外部 -> qt語言家 -> 更新翻譯(lupdate)
以指令行為例:
d:\qt\qt5.7.0\5.7\src\qtbase\src\widgets>lupdate widgets.pro updating ‘widgets.ts’… found 218 source text(s) (218 new and 0 already existing) d:\qt\qt5.7.0\5.7\src\qtbase\src\widgets>
執行 lupdate 之後,就會在 widgets.pro 所在目錄下生成一個 widgets.ts 檔案。
用 qt linguist 打開 widgets.ts,找到需要翻譯的部件,進行翻譯。以 qtextedit 右鍵菜單(複制、粘貼)為例,由于 qtextedit 右鍵菜單通過 qwidgettextcontrol 實作,找到 qwidgettextcontrol。
翻譯相關選項,例如:
&undo -> 撤銷 &red -> 重做 cu&t -> 剪貼 &copy -> 複制 copy &link location -> 複制連結位址 &paste -> 粘貼 delete -> 删除 select all -> 全選
儲存翻譯後的檔案,選擇:檔案 -> 釋出,這時會生成一個名為 widgets.qm 的檔案(也可使用 <code>lrelease widgets.ts</code> 來生成)。
注意:其他 widgets,例如:qlineedit 和 qmessagebox 也可以通過相同方式來翻譯。
使用 qtranslator 加載生成的 widgets.qm 檔案:
至此,程式就可以顯示為指定的語言了。