实现简单的hello翻译

来源:互联网 发布:php大型网站如何维护 编辑:程序博客网 时间:2024/05/14 07:01

 
开发环境:Qt Command Prompt (暂时不使用Qt Create集成开发环境)
 
1.在hello目录下先生成一个hello.cpp文件,并编辑如下代码:
#include <QApplication>
#include <QPushButton>
#include <QTextCodec>
#include <QTranslator>
#include <QObject>
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
 
   //这是第一种翻译的方法
    QTranslator translator;
    translator.load("hello_zh.qm");
    app.installTranslator(&translator);
 
   //这是第二种,先在这里注释,使用第二种翻译的时候会用到
   // QTextCodec::setCodecForCStrings(QTextCodec::codecForName("gb2312"));
   // QTextCodec::setCodecForLocale(QTextCodec::codecForName("gb2312"));
   // QTextCodec::setCodecForTr(QTextCodec::codecForName("gb2312"));
                       // QPushButton::tr   这个必须得加,否则无法翻译
    QPushButton button(QPushButton::tr("hello"));
    button.show();
    QObject::connect(&button, SIGNAL(clicked()), &app, SLOT(quit()));
    return app.exec();
}

2. 在Qt Command Prompt 下进入hello目录,然后运行qmake -project生成一个hello。pro的文件
 
3. 打开刚生成扩展名为pro的QT工程文件,并在文件中添加需要翻译的文件,并在文件结尾处添加如下代码:

TRANSLATIONS = hello_zh.ts     //这就是我们翻译时需要使用的文件,不需翻译时就可以不添加这句了

4.继续在Qt Command Prompt下输入命令:执行命令lupdate hello.pro,生成TS文件,文件中包含要翻译的内容

5.利用QT语言学家(linguist)打开刚才生成的TS文件,对需要翻译的字段进行翻译;

6.利用QT语言学家(linguist)文件菜单中的发布命令,生成扩展名为qm的最终翻译文件;

7.再在代码中添加:

    QTranslator translator;
    translator.load("hello_zh.qm");
    app.installTranslator(&translator);

如最上面那个hello.cpp的代码中已经添加了

8.我们的可执行程序还没生成呢,继续在Qt Command Prompt下输入命令:qmake

9.到这步时,还只是生成了Makefile文件,继续输入命令:mingw32-make  这样就可以在debug目录下生成hello,这就是我们要的可执行程序,这是我们双击运行时可能会报错,原因是因为环境变量没加,我们就把它加进去吧,

我的电脑->属性->高级->环境变量->在用户变量那栏选择path,再点击下面的编辑,添加D:\Qt\2009.05\qt\bin;  //这个要看你qt安装在哪,不可生搬硬套

我们还需要把生成的呢个hello_zh.qm文件拷贝到debug目录下才可以显示翻译,

这样我们再次点击hello时就会显示我们翻译的内容了

 

下面我们来做下第二种方法:

代码如下:

#include <QApplication>
#include <QPushButton>
#include <QTextCodec>
#include <QTranslator>
#include <QObject>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

 //   QTranslator translator;
 //   translator.load("hello_zh.ts");
 //   app.installTranslator(&translator);

 

//这就是第二种方法需要添加的翻译语句

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("gb2312"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("gb2312"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("gb2312"));

                                 //直接输入要实现的中文

    QPushButton button(QPushButton::tr("你好"));
    button.show();
    QObject::connect(&button, SIGNAL(clicked()), &app, SLOT(quit()));

    return app.exec();
}

在Qt Command Prompt依次输入命令:

qmake -project

qmake

mingw32-make

再去debug目录下运行hello即可

 

原创粉丝点击