Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

c++ - How to translate the buttons in qmessagebox?

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

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

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...