How to translate the buttons in qmessagebox?

Nicholas Yu picture Nicholas Yu · Jul 21, 2015 · Viewed 11.8k times · Source

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()?

Answer

Tarod picture Tarod · Jul 22, 2015

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:

  • You can load a different locate creating a new QLocale object and setting it using void QLocale::setDefault(const QLocale & locale). Example.
  • I'm loading 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.
  • Maybe you can find the text you're trying to translate is not translated yet by Qt. In this case, I recommend you to upgrade the Qt version to check if the translation exists in the most recent version or code yourself the change. Some useful links: here and here.