Qt multi-language switching

This article uses Qt Linguist to switch between Chinese and English.

1. Add the following content to the pro file

2. Edit the interface

3. Generate .ts translation files, ts files are actually files in xml format

4. Open the .ts file through Qt Linguist and edit it.

 

  • After modifying the .ts file, you need to publish the translation file, and then the .qm file can be used by the program
  • Method 1: Tools-"External Tools-"Qt Linguist -" Publish the translation, you can open the .ts file in text mode, modify it yourself, and then publish the translation through this method
  • Method 2: Open the .ts file with QtLinguist, file -> publish translation

This is mainly because the text in the default .ui file is in English, if the default is Chinese,

In the above figure, the "source text" on the left should be "file ", and the "Chinese translation" should be file , the "source text" on the right should be " document ", and the "Chinese translation" should be a file .

The default language is Chinese, so the source text of zh_cn.ts (Chinese translation file) is consistent with the translation, and the translation of en_US.ts needs some English translation.

The default language is English, so the source text of en_US.ts (English translation file) is consistent with the translation, and the translation of zh_cn.ts requires some Chinese translation.

Note: If you create the control in the new way in the file, open the .ts file in the Qt language home, the corresponding button phrase and form are code, not Ui.

 

5. Add the .qm file to the resource file

6. Core code:

#pragma execution_character_set("utf-8")
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QTranslator>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QTranslator translator;
    translator.load(":/zh_CN.qm");//en_US
//    qApp->installTranslator(&translator);
//    ui->retranslateUi(this);
    connect(ui->radioButton,SIGNAL(clicked(bool)),this,SLOT(changeLanguage(bool)));
    btn = new QPushButton(tr("测试"),this);
//    btn->setObjectName("btnTest");
    btn->move(00,00);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeLanguage(bool ch)
{
    QTranslator translator;
    if(ch)
    {
        translator.load(":/en_US.qm");
    }
    else
    {
        translator.load(":/zh_CN.qm");

    }
    qApp->installTranslator(&translator);//会触发QEvent::LanguageChange事件
    ui->retranslateUi(this);//用于更新界面,F2可以查看没有更新btn,所以增加如下代码
    btn->setText(tr("测试"));//此步骤很关键。  由于btn不是通过Ui创建的,所以必须增加此代码。
}

7. Screenshot:

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/113846886