Internationalizing Applications
Notice that the languages in Figure 3 are also different. Figure 3(a) is Norwegian, while 3(b) is German (Swiss).
To internationalize applications in Qt:
- Use QString for all user-visible text. Since QString uses Unicode 4.0 encoding internally, every language in the world can be processed transparently using familiar text-processing operations.
- Wherever your program uses "quoted text" for user-visible text, ensure that it is processed by the tr() function.
- Run the application lupdate to extract translatable text from the C++ source code of the Qt application.
- Use Qt Linguist and translate your extracted text to the languages you want to support.
- Run the application lrelease to obtain a lightweight message file suitable for end use.
Step 4 is usually done by a translator (like QT Linguist), while the other steps are done by you.
To switch the language you simply call the QCoreApplication::installTranslator() function. When called during the construction of an application, nothing else is needed for the app to run in the selected language. However, to change the language at runtime, you need to reimplement changeEvent() of the PreviewWindow class to handle LanguageChange:
void changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) { ui.retranslateUi(this); ui.imageName->setTitle (imageCount() ? currentImageName() : tr("no images found")); ui.imageDimension->setText (QString(tr("Dimensions: %1X%2")) .arg(ui.currentImage->pixmap() ? ui.currentImage-> pixmap()->width() : 0) .arg(ui.currentImage->pixmap() ? ui.currentImage->pixmap()-> height() : 0)); } }
You call ui.retranslateUi(this) to translate all the user-visible strings that entered when creating the GUI in Qt Designer. However, you also need to update the widgets that have user-visible strings updated by code. That is why I call setTitle() and setText() for the imageName and imageDimension. Notice how the strings are wrapped inside a tr() function. With this reimplementation of changeEvent(), the application supports changing the language at runtime.