如何翻译qmessagebox中的按钮? [英] How to translate the buttons in qmessagebox?

查看:258
本文介绍了如何翻译qmessagebox中的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的QMessageBox:

QMessageBox::question(this, tr("Sure want to quit?"), 
    tr("Sure to quit?"), QMessageBox::Yes | QMessageBox::No);

我该如何翻译是/否字?因为没有地方放置tr()?

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.

正确的方法是不手动翻译那些字符串. Qt已将翻译包含在translation文件夹中.

The right way is not to manually translate those strings. Qt already includes translations in the translation folder.

想法是加载Qt中包含的翻译(qm文件).

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();
}

注意:

  • 您可以加载其他位置,以创建新的QLocale对象并使用void QLocale::setDefault(const QLocale & locale)进行设置. 示例.
  • 我正在加载qt_*.qmqtbase_*.qm,因为自Qt 5.3起,翻译被拆分为不同的文件.实际上,对于QMessageBox,翻译后的字符串在qtbase_*.qm中.加载两者都是一个好习惯. 更多信息.还有更多qm文件,例如qtquickcontrols_*.qmqtmultimedia_*qm.根据您的要求加载所需的内容.
  • 也许您会发现Qt尚未翻译您要翻译的文本.在这种情况下,建议您升级Qt版本,以检查翻译是否存在于最新版本中,或者自己编写更改.一些有用的链接:此处此处.
  • 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.

这篇关于如何翻译qmessagebox中的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆