1.在工程文件添加 TRANSLATIONS = debug/lang_English.ts debug/lang_Chinese.ts 2.在需要翻译的地方用上tr 例如:setText(tr("hello world")); 3.提供一个更改语言的接口 void MainWindow::changeTr(int language) 4.重载void changeEvent(QEvent *e); 对语言改变事件进行处理 5.利用qt语言家更新翻译,手工翻译生成的.ts文件之后,再进行发布翻译
下面是个简单例子:
//mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QLabel> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void changeEvent(QEvent *e); void changeTr(int language_label); private: Ui::MainWindow *ui; QLabel *label,*label1; }; #endif // MAINWINDOW_H
//mainwindows.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QLabel> #include <QTranslator> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { label = new QLabel(this); label1 = new QLabel(this); label->setText(tr("hello world")); label1->setText(tr("hello")); label1->move(label->x(),label->y()+label->height()); ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeTr(int language_label) { QString qmFilename; static QTranslator* translator; if (translator != NULL) { qApp->removeTranslator(translator); delete translator; translator = NULL; } translator = new QTranslator(this); QString runPath = QCoreApplication::applicationDirPath(); //获取文件运行路径 qDebug() << runPath; if(language_label==1) { qmFilename = runPath + "/lang_Chinese.qm"; } else { qmFilename = runPath + "/lang_English.qm"; } qDebug() << qmFilename; if (translator->load(qmFilename)) { qDebug() << "installTranslator"; qApp->installTranslator(translator); } // ui->retranslateUi(this); // 重新设置界面显示 } void MainWindow::changeEvent(QEvent *e) { // MainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: qDebug() << "changeEvent" << e->type(); label->setText(tr("hello world")); label1->setText(tr("hello")); ui->retranslateUi(this); break; default: break; } }
//main.cpp #include "mainwindow.h" #include <QApplication> #include <QThread> #include "stdlib.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; // w.changeTr(1); w.show(); w.changeTr(1); return a.exec(); }