翻译文件的加载主要有两部分,一个是自己的,另外一个是qt自带的,可以在qt的安装目录下找到!(qt_zh_CN.qm)
一般情况下,我们会把翻译文件都放在一个固定的目录下,下面分享一个接口,指定目录下遍历加载翻译文件!
//加载翻译文件
bool setTranslator(const QString strPath)
{
bool bRet = false;
if (strPath.isEmpty() || !QFile::exists(strPath))
{
return bRet;
}
QTranslator * pTrans = new QTranslator();
if (pTrans->load(strPath))
{
QApplication::installTranslator(pTrans);
bRet = true;
}
else
{
delete pTrans;
pTrans = NULL;
}
return bRet;
}
void searchQmFile(const QString & strPath)
{
QDir dir(strPath);
if (!dir.exists())
{
return;
}
dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
dir.setSorting(QDir::DirsFirst); // 文件夹优先
// 转换成一个List
QFileInfoList list = dir.entryInfoList();
if (list.size() < 1)
{
return;
}
int i = 0;
do
{
QFileInfo fileInfo = list.at(i);
QString tt = fileInfo.fileName();
// 如果是文件夹
bool bisDir = fileInfo.isDir();
if (bisDir)
{
searchQmFile(fileInfo.filePath());
}
else
{
bool bQm = fileInfo.fileName().endsWith(".qm");
setTranslator(fileInfo.filePath());
}
i++;
} while (i < list.size());
}
/将当前目录设置为程序的所在目录
QDir::setCurrent(a.applicationDirPath());
QString strLanPath = QObject::tr("%1\\Language_zh").arg(QDir::currentPath());
strLanPath = QDir::toNativeSeparators(strLanPath);
//读取翻译文件
searchQmFile(strLanPath);