Translation not working for ui->label->setText(QObject::tr(ui->label->text().toStdString().c_str()));
-
Hi All,
Dynamic translation not working for below.
Can you kindly helpWidget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);//Create nw object of QTranslator trans = new QTranslator; // Default language m_strLang = "English"; ui->label->setText(QObject::tr(LABEL)); connect(ui->butEnglish,SIGNAL(clicked(bool)),this, SLOT(setEnglish())); connect(ui->butChinese,SIGNAL(clicked(bool)),this, SLOT(setChinese()));
}
Widget::~Widget()
{
delete ui;
}void Widget::setEnglish()
{
//remove old translation
removeTranslators();//load english and install translator qDebug() <<"English Load:" << trans->load("eng") << endl; qDebug() << "English Install:" << qApp->installTranslator(trans) << endl; // I dont want to hardcode like: ui->label->setText(QObject::tr(LABEL)); // get the text and re-set again for new language QString str = ui->label->text(); ui->label->setText(QObject::tr(str.toStdString().c_str())); m_strLang = "English";
}
void Widget::setChinese()
{
//remove old translation
removeTranslators();//load chinese and install translator qDebug() <<"Load:" << trans->load("chi") << endl; qDebug() << "Install:" << qApp->installTranslator(trans) << endl; // I dont want to hardcode like: ui->label->setText(QObject::tr(LABEL)); // get the text and re-set again for new language QString str = ui->label->text(); ui->label->setText(QObject::tr(ui->label->text().toStdString().c_str())); m_strLang = "Chinese";
}
void Widget::removeTranslators()
{
qDebug() << "remove:" << qApp->removeTranslator(trans) << endl;
} -
Hi and welcome to devnet,
That's not how dynamic translation works.
See the dedicated chapter in Qt's internationalisation documentation.
-
Hi administrator why do you throw this threadTo our section?Is it because it has word"chinese"?
-
@jiancaiyang Please calm down.
This thread hasn't been moved. It was already in this sub-forum. If it had been moved you would see a small arrow beside the title.
-
@SGaist Alright, It is really a Chinese SPECIFIC question.
And I can answer that "translation can be better occurs amongst Qt classes only, so do not mix std c++ style strings together."ui->label->setText(QObject::tr(ui->label->text().toStdString().c_str()));
Could be replaced by:
ui->label->setText(QObject::tr(ui->label->text()));
-
No, not at all. It's a translation specific question which in this case concerns both english and Chinese.
However my answer still applies, overloading the changeEvent like described in the documentation is the correct thing to do:
void MyWidget::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) { titleLabel->setText(tr("Document Title")); ... okPushButton->setText(tr("&OK")); } else QWidget::changeEvent(event); }
It's valid for all languages.