Search code examples
qtqcomboboxmultilingual

Qt Multi language QCombobox


I have got a problem with multi language qt (change language on the fly). My form have a combobox which should be translated when language changed. When languageChanged, the app call method retranslateUi() to translate item in the combobox. The combobox have slot corresponding for signal currentIndexChanged().

void on_comboBox_currentIndexChanged(int index)
{
//do something
}

But when method retranslateUi() called, I do this:

void retranslateUi()
{
ui->comboBox->clear();
ui->comboBox->insertItems(0, QStringList()
         << QApplication::translate("SettingDialog", "English", 0, QApplication::UnicodeUTF8)
         << QApplication::translate("SettingDialog", "French", 0, QApplication::UnicodeUTF8)
        );
}

Problem is: each statement in retranslateUi() will emit the signal currentIndexChanged(), then the slot will call again.

How can I avoid that ?


Solution

  • clear() and insertItems() will trigger the currentIndexchanged(int) SLOT function of combobox as former changes the index to -1 and later will also changes the index as you are inserting items at position 0.

    So restrict on_comboBox_currentIndexChanged(int) by using a flag as follows...

    void on_comboBox_currentIndexChanged(int index)
    {
    if(!retranslateFlag)
    //do something
    }
    
    
    void retranslateUi()
    {
    retranslateFlag = true;
    ui->comboBox->clear();
    ui->comboBox->insertItems(0, QStringList()
         << QApplication::translate("SettingDialog", "English", 0, QApplication::UnicodeUTF8)
         << QApplication::translate("SettingDialog", "French", 0, QApplication::UnicodeUTF8)
        );
    retranslateFlag = false;
    }