Change language at runtime



  • Hi! I'm writing my application by code and I have implemented language change in runtime but I don't have ui.retranslateUi(this) function to change text. I have managed to change some text but problem is how to change combobox items text? Thanks in advance for your help.



  • @Cobra91151
    Hi, friend, welcome devnet.

    There is my way. I hope it can help you.

    1. First, Tow slots function when changed the language
    void MainWindow::StActionLanguageChina()
    {
        mpTranslator->load(":/lg/language/lg_ch.qm");// QTranslator load the language file
        qApp->installTranslator(mpTranslator);
    }
    
    void MainWindow::StActionLanguageEnglish()
    {
        m_pTranslator->load(":/lg/language/lg_en.qm");
        qApp->installTranslator(m_pTranslator);
    }
    
    1. rewrite the changeEvent function
    void MainWindow::changeEvent(QEvent *event)
    {
        //QDialog::changeEvent(event);
        if( QEvent::LanguageChange == event->type() )
        {
            ui->retranslateUi(this);
            ReUiSetText(); // note this function: if you hasn't the ui file, must use this way to translate
        }
    }
    
    1. If hasn't ui file, should use the way.
    void MainWindow::ReUiSetText()
    {
        m_pMenuFile->setTitle(tr("File(&F)"));
        m_pMenuSet->setTitle(tr("Set(&S)"));
        m_pMenuHelp->setTitle(tr("Help(&H)"));
        //...all the language what you want to translate, but not has the ui file. you should rewrite the `set....` at here. to change the language.
    }
    


  • @joeQ
    Thanks but you misunderstood my question. I have already implemented my function Test::appLocalization() in which I change text, the problem is how to change QComboBox items text?

    QComboBox did not have property setTitle.



  • You basically have to re-execute any line of code that calls tr() so in case of QComboBox:

    // QComboBox* comboBox
    auto comboModel = comboBox.model();
    comboModel->setData(comboModel->index(0,0),tr("Option1"));
    comboModel->setData(comboModel->index(1,0),tr("Option2"));
    comboModel->setData(comboModel->index(2,0),tr("Option3"));
    

  • Qt Champions 2016

    That's one thing the designer shines at - retranslating the whole of the static UI automagically ... :)



  • @VRonin

    I have changed your code to:
    comboBox->model()->setData(comboBox->model()->index(0,0), QObject::tr("Text"));

    And now it's retranslating QComboBox. I post it here so others can find the solution. Thank you for your reply.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.