I have a QMessageBox
like this:
QMessageBox::question(this, tr("Sure want to quit?"),
tr("Sure to quit?"), QMessageBox::Yes | QMessageBox::No);
How could I translate the Yes/No word? since there is no place to place a tr()
?
Sorry, I'm late, but there is a best way of solving your issue.
The right way is not to manually translate those strings. Qt already includes translations in the translation
folder.
The idea is to load the translations (qm
files) included in Qt.
I'd like to show you a code to get the message translated according to your locale:
#include <QDebug>
#include <QtWidgets/QApplication>
#include <QMessageBox>
#include <QTranslator>
#include <QLibraryInfo>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTranslator qtTranslator;
if (qtTranslator.load(QLocale::system(),
"qt", "_",
QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
{
qDebug() << "qtTranslator ok";
app.installTranslator(&qtTranslator);
}
QTranslator qtBaseTranslator;
if (qtBaseTranslator.load("qtbase_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
{
qDebug() << "qtBaseTranslator ok";
app.installTranslator(&qtBaseTranslator);
}
QMessageBox::question(0, QObject::tr("Sure want to quit?"), QObject::tr("Sure to quit?"), QMessageBox::Yes | QMessageBox::No);
return app.exec();
}
Notes:
void QLocale::setDefault(const QLocale & locale)
. Example.qt_*.qm
and qtbase_*.qm
because since Qt 5.3 the translations are splited in different files. In fact, for QMessageBox
the translated strings are in qtbase_*.qm
. Loading both is a good practice. More info. There are more qm
files like qtquickcontrols_*.qm
or qtmultimedia_*qm
. Load the required ones according to your requirements.