Using Gettext with the Qt Framework
Monday, June 14th, 2010The Qt Framework for some reason doesn’t provide any built-in support for Gettext, the quasi-standard for translating software programs. An alternative is provided, Qt Linguist, however there are several reasons why some may still prefer Gettext:
- If your application is already partially translated using Gettext it’s much easier to keep on using it rather than converting all your mo/po files to Qt’s format.
- Another significant advantage of Gettext is that it doesn’t have any dependencies (unlike Qt Linguist which creates a dependency to the Qt Framework) and thus allows creating more portable code.
So for these reasons, I’ve created a small library which parses and manages Gettext catalogues in Qt. The library includes a generic parser and a catalogue manager which can be used in any C++ project. On top of that, a Qt wrapper is provided for easy integration with the Qt framework.
The library can be downloaded from the Google Code project:
Download the Gettext library for the Qt Framework
Setting up and using the library is easy:
#include <QtGettext.h> QtGettext::instance()->setLocale("cn_TW"); // Set the locale QtGettext::instance()->setCatalogueName("catalogue"); // Set the name of the mo files QtGettext::instance()->setCatalogueLocation("Data/Locales"); // Set the catalogue folder
QtGettext is now set to use the file in Data/Locales/cn_TW/catalogue.mo
.
Also note that if this file is not available, QtGettext will try to load Data/Locales/cn/catalogue.mo
(if available) as an alternative.
To mark a string for translation, simply call:
QtGettext::instance()->getTranslation("Some string to be translated");
Since this is rather long, a _()
macro is also provided. It shortens the code to just:
_("Some string to be translated");