In my Qt5 application I am trying to switch the language at run-time. So far here my simple function:
QTranslator _translator;
void MainWindow::switchLanguage(QString lang)
{
if (!_translator.isEmpty()) qApp->removeTranslator(&_translator);
if (lang == "it")
{
_translator.load("Language_it_IT.qm", qApp->applicationDirPath());
qApp->installTranslator(&_translator);
}
ui->retranslateUi(this);
}
It works fine, but for the MainWindow
only. Inside I have some form classes (with their UIs) that I load into a QStackedWidget
:
FormMonitor _formMonitor; // they all inherit from QWidget
FormSettings _formSettings; // and have their .ui file
FormProgram _formProgram;
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
// ...
ui->stackedWidget->addWidget(&_formMonitor);
ui->stackedWidget->addWidget(&_formSettings);
ui->stackedWidget->addWidget(&_formProgram);
// ...
}
void MainWindow::loadView(int index)
{
ui->stackedWidget->setCurrentIndex(index);
}
These forms are not translated.
How can I translate all the "nested" forms inside my MainWindow
?
Reimplement the changeEvent
of your form classes like this:
void Form::changeEvent(QEvent *e)
{
if (e->type() == QEvent::LanguageChange)
ui->retranslateUi(this);
QWidget::changeEvent(e);
}