我有这样的东西:
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();
}
什么是避免重复的更好方法?
我试过像这样使用 lambda 函数:
auto func = is_translatable
? [](const char *str) -> QString { return tr(str); }
: [](const char *str) -> QString { return QLatin1String(str); };
但它不起作用。而且看起来不太好。
最佳答案
你可以使用预处理器
#define TRANSLATE(cond, str) (cond) ? tr(str) : QLatin1String(str)
然后使用它,这样您就不再需要外部 if
。
mbox.setWindowsTitle(TRANSLATE(is_translatable, "Title"))
关于c++ - 可选的 Qt 字符串翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327789/