How can I dynamically switch between languages in my application
来源:百度文库 编辑:神马文学网 时间:2024/05/01 18:22:29
How can I dynamically switch between languages in my application using e.g a QComboBox?
Answer:
In order to achieve this, you can create a function, called e.g retranslateUi() that sets the user visible text for your widgets. It is not possible to switch between the languages without having such a function that gets called everytime the language is changed and that returns a translated version of the text by wrapping it with tr().
Now you can connect the triggered(const QString &) signal of your QComboBox to a slot which will load and install the correct translator. Finally you also need to reimplement the changeEvent() to check for a LanguageChange event and call retranslateUi() when it occurs .
See the documentation:
http://doc.trolltech.com/4.3/qevent.html#Type-enumSee the following example for a demonstration:
#includeclass MainWindow : public QMainWindow{ Q_OBJECTpublic: MainWindow() { translator1 = new QTranslator(this); translator2 = new QTranslator(this); menu = new QMenu(this); menuBar()->addMenu(menu); fileAction = new QAction(this); menu->addAction(fileAction); QComboBox *combo = new QComboBox(this); setCentralWidget(combo); combo->addItem("fr"); combo->addItem("en"); combo->addItem("sp"); connect(combo, SIGNAL(activated(const QString &)), this, SLOT(changeMyLanguage(const QString &))); retranslateUi(); } void retranslateUi() { menu->setTitle(tr("File")); fileAction->setText(tr("First action")); } void changeEvent ( QEvent * event ) { if (event->type() == QEvent::LanguageChange) { retranslateUi(); } QMainWindow::changeEvent(event); } public slots: void changeMyLanguage(const QString & string) { if(string == QString("fr")) { translator1->load("t1_fr", "."); qApp->installTranslator(translator1); } if(string == QString("sp")) { translator2->load("t1_sp", "."); qApp->installTranslator(translator2); } if(string == QString("en")){ qApp->removeTranslator(translator1); qApp->removeTranslator(translator2); } }private: QAction *fileAction; QMenu *menu; QTranslator *translator1; QTranslator *translator2;};#include "main.moc"int main(int argc, char **argv){ QApplication a(argc, argv); MainWindow window; window.resize(50, 50); window.show(); return a.exec();}