首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Qt 學習之路 (33):國際化入門——從 tr() 到多語言部署完整實作

     編輯:關於C++

Qt 國際化兩大路線比較

  • QTextCodec:硬編碼編碼名稱,除非全程 Unicode,否則跨平台仍有亂碼風險。
  • tr() 函式 (推薦):原始碼保持 ASCII/UTF-8,翻譯與程式碼分離,支援動態切換,為 Qt 官方最佳實踐。

範例應用:簡單主視窗

mainwindow.cpp:


MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
    QMenuBar *menuBar = new QMenuBar(this);
    QMenu *fileMenu = new QMenu(tr("&File"), menuBar);  // & 產生快捷鍵底線
    QAction *newFile = new QAction(tr("&New..."), fileMenu);
    fileMenu->addAction(newFile);
    QAction *openFile = new QAction(tr("&Open..."), fileMenu);
    fileMenu->addAction(openFile);
    menuBar->addMenu(fileMenu);
    setMenuBar(menuBar);
    connect(openFile, SIGNAL(triggered()), this, SLOT(fileOpen()));
}

void MainWindow::fileOpen() {
    QFileDialog *fileDialog = new QFileDialog(this);  // 建構函式法:Qt 繪製,可翻譯
    fileDialog->setWindowTitle(tr("Open File"));
    fileDialog->setDirectory(".");
    if (fileDialog->exec() == QDialog::Accepted) {
        QString path = fileDialog->selectedFiles()[0];
        QMessageBox::information(NULL, tr("Path"), tr("You selected\n%1").arg(path));
    } else {
        QMessageBox::information(NULL, tr("Path"), tr("You didn't select any files."));
    }
}

關鍵點:

  • & 標記快捷鍵 (Alt+F 開啟 File 選單)。
  • 使用 QFileDialog 建構函式而非靜態函式,前者為 Qt 自繪可翻譯,後者呼叫系統原生對話框難以翻譯。
  • tr("You selected\n%1").arg(path) 正確處理動態參數。

國際化四步驟實作

1. 專案檔加入翻譯宣告


TRANSLATIONS += myapp.ts

2. 執行 lupdate 提取字串


lupdate MyApp.pro

輸出範例:Updating 'myapp.ts'... Found 7 source text(s) (0 already existing)。lupdate 為增量更新,保留既有翻譯,僅處理新增/修改字串。

3. 使用 Qt Linguist 翻譯

  • 開始選單 → Qt → Tools → Qt Linguist。
  • 開啟 .ts 檔,逐項翻譯,完成後工具列「發布」產生 myapp.qm (二進位優化格式)。

Qt Linguist 翻譯介面

4. 載入翻譯檔修改 main()


int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    QTranslator qtTranslator;
    qtTranslator.load("myapp.qm");  // 相對路御:執行檔同目錄
    a.installTranslator(&qtTranslator);
    MainWindow w;
    w.resize(800, 600);
    w.show();
    return a.exec();
}

常見坑:load() 使用相對路徑,若 .qm 不在執行檔目錄會載入失敗 → 介面仍為英文。解決:將 .qm 複製至建置輸出目錄 (如 debug/ 或 release/)。

中文化後介面

動態語言切換基礎

.qm 為動態載入而非編譯嵌入,支援執行時切換:


void switchLanguage(const QString &lang) {
    qApp->removeTranslator(&currentTranslator);
    currentTranslator.load(lang + ".qm");
    qApp->installTranslator(&currentTranslator);
    // 需觸發 UI 重新翻譯:changeEvent(QEvent::LanguageChange) 或重建 UI
}

國際化最佳實踐棢核清單

  1. 所有使用者可見字串包裹 tr()。
  2. 善用 comment 解決多義詞。
  3. 動態參數用 %1~%9 + arg()。
  4. 非 QObject 類別用 QObject::tr() 或 qApp->translate()。
  5. 靜態/全域字串用 QT_TR_NOOP/QT_TRANSLATE_NOOP 標記。
  6. 自繪對話框 (建構函式) 優於系統原生對話框 (靜態函式)。
  7. .qm 隨應用部署,相對路徑載入。
  8. 定期執行 lupdate 同步新增字串。

Qt 國際化機制成熟、工具鏈完整,遵循上述流程即可輕鬆構建多語言應用,支援未來動態切換語言擴充。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved