Localizing special parameters – currencies and dates with QLocale

A common thing you might need to do is localize currencies and dates. Qt makes this easy, although the solution isn't obvious until you've thought about it a bit.

First, you need to know about the QString arg method. It replaces an escaped number with the formatted version of its argument; if we write:

QString s = QString("%1 %2").arg("a").arg("b");

Then, s contains the string "a b". Second, you need to know about the toString method of QLocale which formats its argument in a locale-specific way.

So, we could write:

QString currencyValue = QString("%1 %2")
    .arg(tr("$")).arg(QLocale::toString(value, 'g', 2)

This uses tr to localize the currency symbol and the QLocale class's static method, ...

Get Application Development with Qt Creator - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.