简体   繁体   English

如何使用 Qt 中的单选按钮更改语言? Qtranslator 动态语言

[英]How to change the language with a radioButton in Qt? Qtranslator Dynamic Language

I have a simple app that first asks for language (I have already done the qm and ts files) and it works:我有一个简单的应用程序,它首先询问语言(我已经完成了 qm 和 ts 文件)并且它可以工作:

//main.cpp
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QTranslator T;
    QStringList langs;
    langs << "Espanol" << "English" << "Deutsch";
    const QString lang = QInputDialog::getItem(NULL, "Language", "Select a language", langs);
    if (lang == "English"){
        T.load(":/ingles.qm");
    } else if (lang == "Deutsch"){
        T.load(":/aleman.qm");
    }
    if (lang != "Espanol"){
        a.installTranslator(&T);
    }

    a.setStyle("fusion");
    MainWindow w;
    w.show();

    return a.exec();
}

But I want to change the language with radioButtons inside the MainWindow, is it posible for example to do it in the mainwindow.cpp in?:但是我想在 MainWindow 中使用 radioButtons 更改语言,例如可以在 mainwindow.cpp 中进行吗?:

void MainWindow::on_botoncambiaridioma_clicked()
{
    if (ui->radioButton_2->isChecked()){
      
    }

    if (ui->radioButton_3->isChecked()){
       
    }
}

First, you should remove the previous language, and then install the current language首先,您应该删除以前的语言,然后安装当前语言

void CTest::ChangeLanguage(const QString& language)
{
    QString qmPath;

    if (0 == QString::compare("English", language, Qt::CaseInsensitive))
    {
        qmPath = qApp->applicationDirPath() + "/translations/translation_english.qm";
    }
    else if (0 == QString::compare("Deutsch", language, Qt::CaseInsensitive))
    {
        qmPath = qApp->applicationDirPath() + "/translations/translation_deutsch.qm";
    }
    else if (0 == QString::compare("Espanol", language, Qt::CaseInsensitive))
    {
        qmPath = qApp->applicationDirPath() + "/translations/translation_espanol.qm";
    }

    if (!m_pTranslator.isNull())
    {
        qDebug() << "remove" << qApp->removeTranslator(m_pTranslator.data()) << QDateTime::currentDateTime();
    }

    m_pTranslator = QSharedPointer<QTranslator>(new QTranslator());
    qDebug() << qmPath << "load" << m_pTranslator->load(qmPath);
    qDebug() << "install" << qApp->installTranslator(m_pTranslator.data()) << QDateTime::currentDateTime();
}

Then, you should also respond to the corresponding event然后,您还应该响应相应的事件

void MainWindow::changeEvent(QEvent* event)
{
    switch(event->type())
    {
        case QEvent::LanguageChange:
            ui->retranslateUi(this);
            break;
        default:
            break;
    }

    return QMainWindow::changeEvent(event);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM