How to dynamically transform an application using Qt linguist

35 views Asked by At

I am continuing to work on an old project written in Qt and I need to translate it into different languages.

It is written without using ui and qml.

I created an additional block for selecting the language and inserted it into the settings.

QTransaltion is declared in a new class created by me and from there I try to update the translation of all existing widgets, but the translation is updated only for those objects that are created after my object, where the translation is initialized.

How do I update the widgets I have already created so that the desired language is displayed?

I use qt 5.15, there is an example in the qt 6 documentation, but it is not entirely clear. documentation

LanguageSettingPage::LanguageSettingPage(SettingsDialog* d):
    SettingsPage(d), m_language_translator(new QTranslator(this))
{
    auto* lh = new QHBoxLayout(this);
    lh->addWidget(m_button_it = new QPushButton(tr("Italia")));
    connect(m_button_it, &QPushButton::clicked, this, &LanguageSettingPage::translate);
    lh->addWidget(m_button_eng = new QPushButton(tr("English")));
    connect(m_button_eng, &QPushButton::clicked, this, &LanguageSettingPage::untraslate);
    this->translate();
}
void LanguageSettingPage::translate()
{
    m_language_translator->load("Language_It_it");
    qApp->installTranslator(this->m_language_translator);
}
void LanguageSettingPage::untraslate()
{
    qApp->removeTranslator(this->m_language_translator);
}
1

There are 1 answers

0
Swift - Friday Pie On

QObject::tr finds translated string and returns it at the moment of call. Localization-friendly forms starting from Qt5 require an overidden changeEvent (before v.5 there was a separate handler)

void MyWidget::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::LanguageChange) {
        // update all localized resources.
        titleLabel->setText(tr("Document Title"));
        okPushButton->setText(tr("&OK"));
    } else
        QWidget::changeEvent(event);
}