Search code examples
qtqtranslateqtwidgets

How to retranslate dynamically created widgets?


I want to reload QTranslator in dynamic and then retranslate dynamically created Widgets with "statically attached labels".

e.g. I've got static label alike:

QString AutoplanWorkspace::IMPORT = QPushButton::tr("Import");

and then I create dynamically control with this label:

QPushButton *button1 = new QPushButton(IMPORT)

Also I load new translator like that:

  if (myTranslator.load("C:\\tr.qm")) {
    //myTranslator.setParent(parent);
    qApp->installTranslator(&myTranslator);
  }

From what I can understand I need to reload UI in addition:

controls.retranslateUi(this);

But that dynamic part and static property as well is not in Ui:: and will not be automatically translated as far as I understand it. How can I translate dynamic part by dynamically loading another translator?


Solution

  • In the class containing the push button you should override the changeEvent and in it catch the QEvent::LanguageChange. There you can a) call retranslateUi to dynamically retranslate the texts from your .ui file (which you have already done) and b) also retranslate all manually created strings (e.g. using button1->setText(tr("Import")). If you take a look into the retranslateUi function, you will see that the automatically generated ui file does also simply contain calls to QApplication::translate again for every text set in the designer. This can obviously not be done automatically for the strings defined outside the .ui file, so you will always need to do that manually.