测试程序界面很简单,包括:两个Lable空间和一个pushbutton按钮,工程名称:TranslateTest,编译器:mingw73_64
主要步骤:
1、在ui或是代码中使用英文,同时在提供的要翻译类中要包含:Q_OBJECT宏。我们再此提供了一种方法,构建QObject的派生类,将我们自己所有要翻译的内容都放到该类中:
派生类很简单,如下:
#ifndef CTRANSSTRING_H
#define CTRANSSTRING_H
#include <QObject>class CTransString : public QObject
{Q_OBJECT
};#endif // CTRANSSTRING_H
这样我们在写代码时,不需要使用tr()了,而是使用:CTransString::tr()来代替,将所有要翻译的内容都移到了派生类中。如下:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "CTransString.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::btnclick);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::btnclick(bool bClicked)
{Q_UNUSED(bClicked)ui->label1->setText(CTransString::tr("this is a constant string."));QString strVar = CTransString::tr