QObject::tr("%1").arg(_value);
Here _value is of QString type, which is dynamically generated. Is the above way correct to translate dynamically generated strings as in my code it doesn't seem to work.
QObject::tr("%1").arg(_value);
Here _value is of QString type, which is dynamically generated. Is the above way correct to translate dynamically generated strings as in my code it doesn't seem to work.
There are two steps:
This means using one of
tr()
in a QObject subclassQCoreApplication::translate()
QT_TR_NOOP
/ QT_TRANSLATE_NOOP
lupdate
will extract the strings passed to those functions/macros, and make them available to linguist
for translation.
This is again done by tr()
and QCoreApplication::translate()
. So for instance:
// marking the strings for extraction
static const char *strings[] = {
QT_TRANSLATE_NOOP("MyContext", "hello"),
QT_TRANSLATE_NOOP("MyContext", "world");
};
// performing the translation at runtime
qApp->translate("MyContext", strings[0]);
There's a ton of documentation about the whole process, see here.
You perhaps meant to do:
QObject::trUtf8(QString("%1").arg(_value).toUtf8(), "dynamic1");
You must ensure that your translation file contains all values that _value
can take with the dynamic1
for the disambiguation value, iff you wish to disambiguate them, that is.
Of course, the _value
must be selected from a fixed list of strings anyway - since tr
isn't a human translator, it simply does a lookup of the string in a translation list.
So, you should really do this:
QString value;
select (variant) {
case VarA: value = QObject::tr("foo"); break;
case VarB: value = QObject::tr("bar"); break;
...
}
That way the relevant strings will be included in the translation list.
You're trying to translate _value
in the wrong place. As stated in other answers, QObject::tr()
can't guess by itself how to translate anything. It works only on fixed strings. You should mark constants you're setting _value
to for translation, not _value
itself.