QT multilingual Chinese and English switching

#2023 Blog Star--City Star Leader Activity Opens#       

        This article introduces in detail the use of the Qt language master tool to realize multi-national language switching of Qt programs. For example, create a new interface, pro parameters, update translation , QT prophet translation language , translate Chinese, translate English, release translation, core code, h source code, cpp source code, demonstration effect and other operations.

 The author of this article is original, please attach the source of the article and the link of this article for reprinting.

QT multilingual switching directory

1 New interface

2 pro parameters

3 Update translations

4 QT Prophet translation language

 5 Translate Chinese

 6 translate English

 7 Post translation

8 core code

8.1 .h source code

8.2 .cpp source code

9 demo effect


1 New interface

2 pro parameters

        pro file to add language file

TRANSLATIONS =  LanguageChinese.ts \
                LanguageEnglish.ts

3 Update translations

        QT Prophet update translation

4 QT Prophet translation language

 5 Translate Chinese

        Open the translation file -> target language Chinese -> write both the original text and the translation in Chinese -> confirm all -> save

 

 6 translate English

        Open the translation file -> target language Chinese -> write both the original text and the translation in Chinese -> confirm all -> save

 

 

 7 Post translation

 

8 core code

8.1 .h source code

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QFile>
#include <QDebug>
#include <QTranslator>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

    void on_pushButton_2_clicked();

private:
    Ui::MainWindow *ui;

    QString strFile;
    QTranslator ch;
    QTranslator en;
};
#endif // MAINWINDOW_H

8.2 .cpp source code

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    strFile = "E:/QT/Creator/QLanguage/";
    //加载 翻译文件
    ch.load(strFile + "LanguageChinese.qm");
    en.load(strFile + "LanguageEnglish.qm");
}

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

//中文
void MainWindow::on_pushButton_clicked()
{
    qApp->installTranslator(&ch);
    ui->retranslateUi(this);
}
//英文
void MainWindow::on_pushButton_2_clicked()
{
    qApp->installTranslator(&en);
    ui->retranslateUi(this);
}

9 demo effect

10 other methods

        You can also use ini files and xml files to achieve the same function, and create two new fields to obtain different fields through global judgment to achieve multi-language switching.

Guess you like

Origin blog.csdn.net/qq_37529913/article/details/131336289