qt 多语言和动态切换
一、使用
生成ts文件
添加需要翻译的地方
1.打开ui文件添加一个button,修改此处的按钮文本和澄清还有注释,勾选可翻译的(默认为勾选状态)。
或者是一段代码。如果是程序中需要翻译的部分需要在该处的字符串设置使用tr(“”)。如下
#include# "QtGuiApplication1.h"
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.pushButton_2->setText(tr("dddddd"));
}
2.当产生更改时需要单击此处更新ts文件。
设置译文
1.双击该文件,打开QT语言家,可以看到刚才添加到button的显示文本和对应注释等。在下方编辑对应译文。
程序中添加的需要翻译的部位如下
动态语言切换
1.生成qm文件
2.如果需要动态切换可按照如下方式加载qm文件
#include# "QtGuiApplication1.h"
#include# <QPushButton>
#include# <QTranslator>
QtGuiApplication1::QtGuiApplication1(QWidget* parent)
: QMainWindow(parent)
{
ui.setupUi(this);
ui.pushButton_2->setText(tr("dddddd"));
connect(ui.pushButton_3, &QPushButton::clicked, this, [=] {
QTranslator chinese;
if (chinese.load(R"(C:\Users\Desktop\QtGuiApplication1\QtGuiApplication1\qtguiapplication1_zh.qm)"))//加载翻译文件
{
qApp->installTranslator(&chinese);//安装翻译包
ui.retranslateUi(this);//刷新界面显示
}
});
}
二、其他应用
存储翻译后的字符
使用下列方式,不管经过何种翻译,name中的字符始终为"Add Plant"
QString name = tr("Add Plant");
使用下列方式,name中的字符会使用翻译文件中的译文
static const char* greeting_strings[] = {QT_TR_NOOP("Add Plant")};
QString name = tr(greeting_strings[0]);
tr简介
QString QObject::tr(const char *sourceText, const char *disambiguation = Q_OBJECT, int n = Q_OBJECT)
-
第一个参数为,要翻译的原始内容
-
第二个参数为,给翻译者的注释内容
-
第三个参数为,可更改的变量n
int n = 3; showMessage(tr("I have %n book(s).", "", n));
参考文章
官方文档翻译 https://zhuanlan.zhihu.com/p/44536503
博客简介 https://blog.csdn.net/qijingbo123/article/details/86573740
三、遇到过的问题
3.1 翻译不生效
集成了QObject的类代码中使用tr包裹了指定字符串,也使用qt语言家进行了翻译。但翻译就是不生效。因为类的头文件没有使用Q_OBJECT导致,或者使用Object::tr(…)调用也可以解决
3.2 对话框qdialogbuttonbox 翻译无法识别
办法1、手动设置【推荐】
//将buttonbox中的ok/cancel/apply变成中文
ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("确定"));
ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("取消"));
ui->buttonBox->button(QDialogButtonBox::Apply)->setText(tr("应用"));
办法2、在qt安装找到qt_zh_CN.ts,里面手动添加:
<context>
<name>QPlatformTheme</name>
<message>
<location filename="../src/widgets/qdialogbuttonbox.cpp" line="+42"/>
<location line="+18"/>
<source>OK</source>
<translation>确定</translation>
</message>
<message>
<location line="+54"/>
<source>Cancel</source>
<translation>取消</translation>
</message>
.....
</context>
然后再生成qt_zh_CN.qm文件
3.3 使用脚本发布qm文件
cd /d "D:\qt\5.13.2\msvc2017_64\bin"
lrelease.exe -verbose "..\test_zh.ts" -qm "..\test_zh.qm"