sikmir sikmir -4 years ago 213
C++ Question

Optional Qt string translation

I have something like this:

void FooWidget:showSomeDialog(bool is_translatable)
{
QMessageBox mbox(this);
if (is_translatable)
{
mbox.setWindowsTitle(tr("Title"));
mbox.setText(tr("Text"));
mbox.setInformativeText(tr("InformativeText"));
mbox.addButton(tr("Button1"), QMessageBox::YesRole);
mbox.addButton(tr("Button2"), QMessageBox::NoRole);
...
} else {
mbox.setWindowsTitle(QLatin1String("Title"));
mbox.setText(QLatin1String("Text"));
mbox.setInformativeText(QLatin1String("InformativeText"));
mbox.addButton(QLatin1String("Button1"), QMessageBox::YesRole);
mbox.addButton(QLatin1String("Button2"), QMessageBox::NoRole);
...
}
mbox.exec();
}


What is a better way to avoid duplication?

I've tried to use lambda function like this:

auto func = is_translatable
? [](const char *str) -> QString { return tr(str); }
: [](const char *str) -> QString { return QLatin1String(str); };


But it doesn't work. Moreover it doesn't look quite good.

Answer Source

You could use the preprocessor

#define TRANSLATE(cond, str) (cond) ? tr(str) : QLatin1String(str)

and then use that so you don't need the outer ifanymore.

mbox.setWindowsTitle(TRANSLATE(is_translatable, "Title"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download