Tuesday, April 12, 2011

How to : QT Hello world localization and I18N

When you installed QT SDK, it came with several useful tools to do the I18N and localization, I’ll put a very basic QT program and show the basic steps to localize the app to support different local /languages.

Create a Basic QT hello world application, make sure all user-visible strings are used as translatable strings (using tr function)
Create a empty QT Project using QT creator,
image
then add a new source file,

image

#include <QtGui>

int main(int argc, char * argv[])
{
    QApplication app(argc,argv);
    QPushButton * button=new QPushButton(QObject::tr("Hello,World!"));
    button->show();
    app.exec();
}

then run the app by pressing F5, you will see the hello world button,
 image

Now we are going to add the Chinese and Japanese Support to the app.

>>> go the the project folder, Run a command called Lupdate(include in the sdk ), to extract all translatable strings to a file,
image

here default.ts is just a xml file as the content bellows,
image

>>>now use the linguist tool to translate it into Japanese, run “linguist” In the qt shell or click the tool from start-menu
open the default.ts, and chose Japanese as the target language,
image

put the translation for hello world in Japanese, and click to mark done, then Save it as  as jp.ts
image

Now quite the translation tool and start over again to translate it to Chinese, and export to cn.ts
>>>compile the cn.ts and jp.ts to binary format using lrelease
image

>>> now in the app, load those two qm files,

QApplication app(argc,argv);

QTranslator translator ;

QLocale curent;
if(curent==QLocale::Chinese)
{
translator.load("F:\\helloworld\\cn.qm");
app.installTranslator(&translator);
}
if(curent==QLocale::Japanese)
{
translator.load("F:\\helloworld\\jp.qm");
app.installTranslator(&translator);
}

QPushButton * button=new QPushButton(QObject::tr("Hello,World"));
button->show();
app.exec();


Now, if you setup your current locale to Japanese, you will see the JP version of helloword

or you can change the default local in code,

QLocale::setDefault(QLocale::Japanese);

 

image image

No comments:

 
Locations of visitors to this page