Question

I'm developing Qt UI application and localizing the UI strings. In my application, I'm using QLabel and setting the texts dynamically. I experimented two ways of setting the texts for localization. While executing the application, I could see, in my first approach strings are getting localized but in second approach they are not.

//Approach 1:
//ui.cpp
//Directly hardcoding the values
labelBox1->setText(QApplication::translate("context","test string"));

//Approach 2:
//UI_Consts.h
static const QString str = QT_TRANSLATE_NOOP("Context","Test String");
//variable 'str' is in global scope

//ui.cpp
#include "UI_Consts.h"
...
labelBox1->setText(str);

When I debugged why second approach not worked, I found that global variables are initialized before the execution of main function. We generally write code for Translation in main() and hence those global variables are not getting translated. I prefer second approach as we can list down all the UI strings in a single file and easily maintain them. I want to know is there any way to localize the strings which are declared in Global Scope(like used in my second approach)?

Était-ce utile?

La solution

Well, that's not the way Qt's translation system is meant to be used...

But if you want to do it that way you could write a function (or implement a class/struct holding all strings) that initializes all your string variables after loading the translations in main() - of course this would result in even more code :D

Autres conseils

I think you've misunderstood what for is QT_TRANSLATE_NOOP. In the Qt Linguist Manual: Programmers you can read under the section: Using QT_TR_NOOP() and QT_TRANSLATE_NOOP()

If you need to have translatable text completely outside a function, there are two macros to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). These macros merely mark the text for extraction by lupdate. The macros expand to just the text (without the context).

So, the problem isn't the global variable str.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top