Translation does not work when the text of QLineEdit is modified
-
I have a desktop application I want to translate. All translations work well except in the following case. I have a QLineEdit object called resultEdit whose text is updated when a pushbutton is clicked on. resultEdit can display the following strings:
const QString days[7] = {QCoreApplication::tr("Monday"), \ QCoreApplication::tr("Tuesday"), \ QCoreApplication::tr("Wednesday"), \ QCoreApplication::tr("Thursday"), \ QCoreApplication::tr("Friday"), \ QCoreApplication::tr("Saturday"), \ QCoreApplication::tr("Sunday")};
So days is a global array. One callback functions which calculates which day to print is
void ZellerGUI::on_yearEdit_editingFinished() { // Calculate the day of the week int calculatedDay = some_integer_from_1_to_7; ui->resultEdit->setText(days[calculatedDay - 1]); }
However, when I select the translation, the names of the days remain in English. It is weird as all other stings are translated well. When I opened the Linguist, it recognised all seven days. What happens in the background that the translations do not work for this global array?
-
@kshegunov I just used your previous solution:
QString day = QCoreApplication::tr(days[calculatedDay - 1]);
Using your last command
QString day = QCoreApplication::translate("Weekdays", days[calculatedDay - 1]);
perfectly works. Now I just have to think it over why it works.
Thank you very much for your precious help!
-
Could it be that static string is built into the binary so it is not being initialized after you load translation QM file?
-
This is rather inner working of C++ itself. But I am only guessing to be honest.
What you can try is to define this string array (btw. you can also use QStringList) in a singleton class that is initialized after translation is loaded, so that it gets correct data.
-
Try something like this:
const char * const days[7] = { QT_TR_NOOP("Monday"), QT_TR_NOOP("Tuesday"), // ... and so on } void ZellerGUI::on_yearEdit_editingFinished() { // ... calculate day QString day = QCoreApplication::tr(days[calculatedDay - 1]); ui->resultEdit->setText(day); }
-
@kshegunov I just used your previous solution:
QString day = QCoreApplication::tr(days[calculatedDay - 1]);
Using your last command
QString day = QCoreApplication::translate("Weekdays", days[calculatedDay - 1]);
perfectly works. Now I just have to think it over why it works.
Thank you very much for your precious help!
-
You're welcome.
Happy coding!Edit:
Btw, moving the keys to the function should also work:void ZellerGUI::on_yearEdit_editingFinished() { // If this is initialized here it should work okay static const char * const days[7] = { QT_TR_NOOP("Monday"), QT_TR_NOOP("Tuesday"), // ... and so on }; // ... calculate day QString day = QCoreApplication::tr(days[calculatedDay - 1]); ui->resultEdit->setText(day); }