Friday, July 2, 2010

Dynamic translations with substituting arguments

I already expressed the importance of developing localized applications, in particular, using the tools provided by Qt framework for translating strings. From time to time, you'll be dealing with phrases that may include some dynamic text, it is, you likely don't know the exact phrase at translation time. For such situations, you may resort to variables within the phrases.

The idea is to generate placeholders in the source text by means of the percentage sign plus a digit, so those %1, %2 and so on items will be replaced at runtime. We can take advantage of the QString::arg() functions which provide us with a simple means for substituting arguments, see example:

void Tester::updateStatus(const QString &testSuiteName, int currentTest, int totalTests)
    label.setText(tr("Testing suite: %1. Current test %2 of %3")

As we can see, the placeholders will take the values for the arguments passed to the method at each invokation.

One good thing about using substituting arguments is the fact that some languages may reverse the phrase (just to cope with plural forms and/or gender, but even when the translator will provide a translated phrase with the placeholders in a different order, the arg() functions will stay the same without need to change the source code of the application.

As far as the placeholders keep the proper numbering, they will be replaced by the supplied arguments in order.

Good dynamic translations!

No comments:

Post a Comment