How to do dynamic translations if we pass strings as text to widgets constructor.
-
Hello All,
I am creating an application with a ability to have multiple language. It works pretty well if I load translations file on start in main function.
But now I want to implement, dynamic translation. I am following Qts documents and some example. So I have implemented language change event in main window class like this
void MainWindow::changeEvent(QEvent* event) { if(0 != event) { switch(event->type()) { // this event is send if a translator is loaded case QEvent::LanguageChange: ui.retranslateUi(this); break; }
and for any widget I have to follow this code :
void MyWidget::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) { titleLabel->setText(tr("Document Title")); ... okPushButton->setText(tr("&OK")); } else QWidget::changeEvent(event); }
but now problem with this code is text should be defined within the widget class, but for my case my all widgets are isolated with a business logic. I create instance of a widget and I pass text as a parameter to them. All text are pre defined in header file with tr keyword.
so is there any other way to do dynamic translation and make widgets to update with new translation words ?
Thanks in advance.
-
Just pass the same parameters again, they should get translated correctly if your single-header is correctly implemented
Thanks for your reply.
What to do mean by if single header is correctly implemented ? I just have bunch statement like this
#define ABC QObject::tr("abc")
like this. I guess it shouldnt be like this ?
-
You need to use the method described here: http://doc.qt.io/qt-5/i18n-source-translation.html#using-qt-tr-noop-and-qt-translate-noop-in-c
They use a
static char*[]
in the example but it's exactly the same with a defined string -
Thanks for your reply.
What to do mean by if single header is correctly implemented ? I just have bunch statement like this
#define ABC QObject::tr("abc")
like this. I guess it shouldnt be like this ?
@PoonamGupta
Since it is usingQObject::tr("abc")
, it looks like it will get a newly-translated string by callingtr()
afresh. So long as code hasn't cached the old value somewhere and instead re-uses your macro each time it should be good to go. -
@PoonamGupta
Since it is usingQObject::tr("abc")
, it looks like it will get a newly-translated string by callingtr()
afresh. So long as code hasn't cached the old value somewhere and instead re-uses your macro each time it should be good to go.@JonB
Thanks for the help.
Yes I kept my original string as a member variable to a class and then I am assigning text to a widget using QObject::Tr(sourceText).
It resolves my issue.