In an application developed in Qt I have a non-visual class (that is, it is not inherited from a QWidget
) but it handles text strings that must be presented to the user. To use the Qt translation engine, I defined all strings using the QApplication::tr()
function.
The strings are correctly displayed in the Linguist
tool, under the context of QApplication
(as expected - see image below). However, when using code I change the Locale
of the application, only the strings under the context of MainWindow
are changed.
ThecodeIusetochangethelanguageisasfollows:
void MainWindow::setLocale(QString sLocale)
{
QTranslator *pTranslator = m_mpTranslators[sLocale];
if(pTranslator)
{
for(map<QString, QTranslator*>::iterator it = m_mpTranslators.begin(); it != m_mpTranslators.end(); ++it)
{
qApp->removeTranslator(it->second);
QApplication::removeTranslator(it->second); // Essa linha não existia antes!
}
qApp->installTranslator(pTranslator);
QApplication::installTranslator(pTranslator); // Essa linha também não!
if(sLocale == "pt_BR")
m_pLocaleButton->menuAction()->setIcon(QIcon(":/resources/icons/pt_BR"));
else
m_pLocaleButton->menuAction()->setIcon(QIcon(":/resources/icons/en_UK"));
ui->retranslateUi(this);
updateUI();
}
}
I think it's important to note that changing text in the graphical interface is immediate (via ui->retranslateUi(this)
and updateUI()
calls), but non-visual class calls occur after the locale , then the text should be translated correctly.
In the code above, I also included the lines marked with comments, but that did not cause the translation to accompany the locale defined.
Does anyone have any idea where I might be mistaken?
Editing:
The version of Qt is 5.1.0 (32 bit), and I'm running on Windows 7 (64 bit). Translators are created in the constructor of class MainWindow
, as follows:
// Setup the translation system
QTranslator *pPortuguese = new QTranslator(this);
QString sPortuguese = QCoreApplication::applicationFilePath().replace(".exe", "_pt_BR.qm");
if(pPortuguese->load(sPortuguese))
m_mpTranslators.insert(map<QString, QTranslator*>::value_type(QString("pt_BR"), pPortuguese));
else
qWarning() << "Portuguese translation file not found";
QTranslator *pEnglish = new QTranslator(this);
QString sEnglish = QCoreApplication::applicationFilePath().replace(".exe", "_en_UK.qm");
if(pEnglish->load(sEnglish))
m_mpTranslators.insert(map<QString, QTranslator*>::value_type(QString("en_UK"), pEnglish));
else
qWarning() << "English translation file not found";
The m_mpTranslators attribute is a simple map that relates the locale string to the translator: std::map<QString, QTranslator*> m_mpTranslators;