This article describesQt dynamic SwitchingLanguage. When writing an international program, in many cases, it is selected during the system startup process.LanguageAnd then load the corresponding locationLanguageTranslate files to implementLanguage.
However, some users need to perform dynamic operations.Language Switching(Dynamic Language Switching), that is, after the program master> body is running, you need to change the Language options. The user does not wantLanguage SwitchingThe program is restarted or the window is closed.
QtThe international design provides this possibility. To achieve this kind of dynamicSwitch, You just need to use a little trick in the program, instead of callingQtThe tr code of the translation statement is concentrated in a function unrelated to form changes, such as retranslateStrings. ChangingLanguageYou can call this function.
The following is a demo program attached, which is only used to prove the function. The Code rigor is not considered too much.
- //dialog.cpp
-
- #include
- #include "dialog.h"
- Dialog::Dialog(QWidget *parent)
- : QDialog(parent)
- {
- label=new QLabel(this);
- okButton=new QPushButton(this);
- connect(okButton,SIGNAL(clicked()),this,SLOT(switchlang()));
- flag=0;
- retranslateStrings();
-
- QVBoxLayout *mainLayout = new QVBoxLayout;
- mainLayout->addWidget(label);
- mainLayout->addWidget(okButton);
- setLayout(mainLayout);
- }
-
- void Dialog::retranslateStrings()
- {
- label->setText(tr("Name:"));
- okButton->setText(tr("Switch Language"));
- setWindowTitle(tr("Switch Language ..."));
- }
-
- void Dialog::switchlang()
- {
- QTranslator translator;
- if(0==flag){
- translator.load("switchlang_zh");
- flag=1;
- }else
- {
- flag=0;
- }
- qApp->installTranslator(&translator);
- retranslateStrings();
- }
- //dialog.h
- #ifndef DIALOG_H
- #define DIALOG_H
- #include
- class QLabel;
- class QPushButton;
-
- //! [0]
- class Dialog : public QDialog
- {
- Q_OBJECT
- public:
- Dialog(QWidget *parent = 0);
- private:
- QLabel *label;
- QPushButton *okButton;
- int flag;
- private slots:
- void retranslateStrings();
- void switchlang();
- };
- //! [0]
- #endif
- //main.cpp
- #include
- #include "dialog.h"
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
- Dialog dialog;
- dialog.show();
- return app.exec();
- }
- //switchlang.pro
- TEMPLATE = app
- TARGET =
- DEPENDPATH += .
- INCLUDEPATH += .
- # Input
- HEADERS += dialog.h
- SOURCES += dialog.cpp main.cpp
- TRANSLATIONS+=switchlang_zh.ts
Summary: