Including localized strings in your application

In order to supply translated strings to the tr and qsTr functions in your application, your application needs to include a QTranslator object to read the .qm files and replace the strings provided to tr and qsTr with their translated counterparts.

We can do this in your main entry point function, as follows:

QApplication a(argc, argv); 
QTranslator translator; 
bool result = translator.load("QtLinguistExample-epo.qm"); 
a.installTranslator(&translator); 
 
    // Other window setup stuff goes here 
     
return a.exec(); 

This code allocates a QTranslator object and loads the indicated translation file into the translator before installing it into the QApplication object. In this example, we're hardcoding the language in order to localize to Esperanto.

Note that if you want to support the locale as picked by the system, you might choose to do it this way:

QString locale = QLocale::system().name(); 
QTranslator translator; 
translator.load(QString("QtLinguistExample-") + locale); 

The QLocale class here is a class for managing the system's locale. Here, we use it to determine the system's locale, and then we attempt to load the localized string file for the system's current locale.

For this to work, the .qm files for the application need to be locatable by the application. They should be in the output directory; one way to do this during development is to turn off shadow builds in Qt Creator, under Build Settings in the Project pane. Building your application installer is a platform-specific task outside the scope of this book for which you need to include .qm files with the application binary.

For more information on Qt Linguist, refer to its manual at https://doc.qt.io/qt-5/qtlinguist-index.html.

Next, we will see how to localize a few special parameters to suit our requirements.