How to translate language in Qt on the fly

前端 未结 1 901
无人共我
无人共我 2020-12-17 04:30

I am using Translator and linguist to translate language in my application in Qt symbain, But I want to do this on the fly (on run time), I have tried the solution given by

相关标签:
1条回答
  • 2020-12-17 04:45

    The link you gave states:

    However, the basic principle is to override QWidget::changeEvent() in every widget which has to be aware of dynamic language changes.

    This is required as installTranslator() will create a change event which will be sent to every single widget. This means, if you want your MainWindow to be retranslated, you have to do:

    void MainWindow::changeEvent(QEvent* event)
    {
        if (event->type() == QEvent::LanguageChange)
        {
            // retranslate designer form (single inheritance approach)
            ui.retranslateUi(this);
        }
    
        // remember to call base class implementation
        QMainWindow::changeEvent(event);
    }
    

    You have to do this for every widget which has a translatable GUI

    [Edit - Added comment as it was the actual answer to the question]

    Don't call setLanguage() from within changeEvent()! You should call setLanguage() from wherever you can change the language. setLanguage() calls LanguageTranslator::loadTranslation() which calls QApplication::installTranslator() which creates a LanguageChange Event which is then caught in MainWindow::changeEvent

    0 讨论(0)
提交回复
热议问题