PaulG
PaulG

Reputation: 7102

Qt Localization with a variable

I would like to translate weather conditions in my code but am having a little trouble.

Example:

English - Cloudy

French - Nuageux

weatherString = hash["weather"];
weatherBytes = weatherString.toLocal8Bit();
weatherCharArray = weatherBytes.data();

qDebug() << "Current Weather: " << QObject::tr(weatherCharArray);

The weather comes in from a web service so it's always different. I knew that the code above would not create the entries automatically in my .ts files as they are only known at runtime, so I tried to manually enter them.

<message>
<source>Cloudy</source>
<translation>Nuageux</translation>
</message>

But everytime I compile it puts in:

type="obsolete"

In my translation tag, what should I do??

Upvotes: 0

Views: 825

Answers (1)

phyatt
phyatt

Reputation: 19112

Here is one of the ways I have implemented a solution to this problem.

// setup (in my constructor before any use of mytr function
this->availableTranslations();

In my cpp file...

QMap <QString, QString> SettingsWidget::trMap;

void SettingsWidget::availableTranslations()
{
     if(trMap.size() != 0)
          return;
     trMap["true"] = tr("True","settings option");
     trMap["false"] = tr("False","settings option");
     trMap["Auto"] = tr("Auto","settings option");
     trMap["None"] = tr("None","settings option");
     trMap["smallest"] = tr("Smallest","settings option");
     trMap["very small"] = tr("Very Small","settings option");
     trMap["small"] = tr("Small","settings option");
     trMap["medium"] = tr("Medium","settings option");
     trMap["large"] = tr("Large","settings option");
     trMap["very large"] = tr("Very Large","settings option");
     trMap["Advanced"] = tr("Advanced","settings option");
     trMap["Basic"] = tr("Basic","settings option");
}

QString SettingsWidget::mytr(QString s)
{
     if(trMap.contains(s))
          return trMap[s];//qApp->translate("SettingsWidget",qPrintable(s));
     else
          return s;
}

Then when I am using the above on the fly it looks like this:

// in use
mytr(list.at(currIndex));

You will notice that with this setup, it can look up a translation based on a variable instead of only a char *, and it puts it in the translation file properly without too much extra work or maintenance.

Hope that helps.

Upvotes: 1

Related Questions