Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
768 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...