用Qt creator找到翻译的目录

Find the directory of a translation with Qt creator

本文关键字:翻译 Qt creator      更新时间:2023-10-16

我是Qt creator的新手,我最近学习了如何使用Qt linguist。当我想要加载翻译时,我需要指定一个在我的计算机上没有问题的目录。但是当我把这个Qt项目给别人的时候,目录改变了,翻译没有出现。

我尝试使用不同的方法,如QDir::currentPath(),但它给了我包含应用程序的构建文件夹的路径。我需要访问的是项目所在的文件夹与翻译的文件和翻译的二进制文件(file_fr.)。qm file_es.qm)。

提前感谢您的帮助:-)

解决方案:

为了获得可执行文件的路径,使用以下方法:

QCoreApplication::applicationDirPath()

例子:

您正在部署位于可执行路径的lang文件夹中的翻译文件:

const QString LANGPATH(QCoreApplication::applicationDirPath() + "/lang");
QTranslator *translator = new QTranslator(this);
translator->load("file_fr.qm", LANGPATH);
QCoreApplication::installTranslator(translator);

你的错误:

您使用的是QDir::currentPath(),但其结果是当前工作目录,而不是包含您的可执行文件的目录。

我设法用Qt资源系统做到了这一点,如果你正在寻找一个简短的教程,你可以找到一个解释如何设置资源的链接。

这是我的代码,如果它可以帮助你:

#include <QApplication>
#include "ClassGenerator.h"
#include "ClassCode.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QString locale = QLocale::system().name().section('_', 0, 0);
QTranslator translator;
translator.load(":/Translation/TPClassGenerator_"+locale+".qm");
app.installTranslator(&translator);
ClassGenerator Window;
Window.show();
return app.exec();
}

正如您所看到的,系统的语言被检索并用于在文件夹资源中选择正确的翻译。

谢谢你的建议:-)