国际化
国际化
使用 Qt 的国际化工具的方式为:
find_package(Qt5 COMPONENTS LinguistTools)
if(Qt5LinguistTools_FOUND)
file(GLOB TS_FILES "${CMAKE_SOURCE_DIR}/assets/*.ts")
qt5_create_translation(QM_FILES "${CMAKE_SOURCE_DIR}/src" ${TS_FILES})
else()
set(QM_FILES "")
endif()
add_library(test MODULE ${QM_FILES})
其中, TS_FILES 需要本身就已经存在,创建的方式是 lupdate-qt5 ${CMAKE_CURRENT_SOURCE_DIR} -ts main.ts
,然后使用 main.ts 拷贝成 xxx.en.ts, xxx.zh.ts 等
另外,还需要将 QM_FILES 安装的到某个路径下
动态字符串的翻译
所谓动态字符串,就是从文件中加载的字符串。现在对其进行翻译
实际上很简单,因为 tr 函数的第一个参数是 const char* ,直接把 QString 转成 char* 传进去就行了,然后手动编辑 ts 文件,在里面添加需要翻译的字符串。唯一需要注意的是字符串两边的 n 需要去掉:
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QTextStream>
#include <QTranslator>
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QTranslator translator;
// clang-format off
if(translator.load("trans_cn.qm")) app.installTranslator(&translator);
else qDebug() << "翻译文件加载失败";
// clang-format on
qDebug() << QObject::tr("hello");
// 从文件中加载
QFile file("1.conf");
file.open(QIODevice::ReadOnly);
QString data = file.readAll();
data.replace("\n", "");
file.close();
qDebug() << "没翻译之前是:" << data;
qDebug() << "翻译之后是:" << QObject::tr(data.toStdString().c_str());
qDebug() << QObject::tr("string with args %1").arg(10);
return app.exec();
}
1.conf 的内容是 :
name
trans.ts 的内容是
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>QObject</name>
<message>
<location filename="main.cpp" line="12"/>
<source>hello</source>
<translation type="unfinished">你好</translation>
</message>
<message>
<location filename="main.cpp" line="12"/>
<source>name</source>
<translation type="unfinished">名字</translation>
</message>
<message>
<location filename="main.cpp" line="12"/>
<source>string with args %1</source>
<translation type="unfinished">带参数的字符串 %1</translation>
</message>
</context>
</TS>
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(trans_qt)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
find_package(Qt5 COMPONENTS Core LinguistTools REQUIRED)
qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} trans_cn.ts)
qt5_add_translation(qmFiles trans_cn.ts)
add_executable(trans_qt main.cpp ${qmFiles})
target_include_directories(trans_qt PRIVATE Qt5::Core)
target_link_libraries(trans_qt PRIVATE Qt5::Core)
install(TARGETS trans_qt RUNTIME DESTINATION bin)