Search code examples
c++qtinternationalization

Protect myself against forgetting to enclose string literals in tr()


Qt uses the tr() function for internationalization, but it is easy to forget to enclose a string with it, for example writing label->setText("Name:"); instead of label->setText(tr("Name:"));.

I remember reading somewhere that you can make QString show an error unless you explicitly enclose the string in some other way (in QLatin1String if I remember correctly). How can I do that?


Solution

  • you can add QT_NO_CAST_FROM_ASCII to DEFINES in the *.pro file. This will prevent automatic conversion from char*. Similarly there is a QT_NO_CAST_TO_ASCII that prevents QStrings being implicitly cast to char*.

    See https://doc.qt.io/qt-5/qstring.html#converting-between-8-bit-strings-and-unicode-strings for more details