最近刚学这做linux下Qt的语言切换,我参考网上的资料,编了个简单的程序实现语言切换,不用重新启动应用程序就能实现语言切换。
下面是我的代码
#include "maindialog.h"
maindialog::maindialog(QWidget *parent)
:
QDialog(parent)
{
date=new
QLabel;//(this);
time=new
QLabel;//(this);
timer=new
QTimer(this);
closeButton=new QPushButton(this);
switchlanguage=new QPushButton(this);
initslot();
languageflag=0;
retranslateStrings();
QHBoxLayout *hlayoutup=new QHBoxLayout;
hlayoutup->addWidget(date);
hlayoutup->addWidget(time);
hlayoutup->addWidget(switchlanguage);
QHBoxLayout *hlayoutdown=new QHBoxLayout;
hlayoutdown->addWidget(closeButton);
QVBoxLayout *mainlayout=new QVBoxLayout;//(this);
mainlayout->addLayout(hlayoutup);
mainlayout->addLayout(hlayoutdown);
setLayout(mainlayout);
}
maindialog::~maindialog()
{
}
void maindialog::initslot()
{
connect(timer,SIGNAL(timeout()),this,SLOT(timer_deal_slot_function()));
timer->start(1000);
connect(closeButton,SIGNAL(clicked()),this,SLOT(close()));
connect(switchlanguage,SIGNAL(clicked()),this,SLOT(switchlanguage_clicked()));
}
void maindialog::retranslateStrings()
{
closeButton->setText(tr("close"));
setWindowTitle(tr("Switch Language ..."));
switchlanguage->setText(tr("Switch
language"));
}
void maindialog::switchlanguage_clicked()
{
QTranslator translator;
if(0==languageflag)
{
translator.load("switchlang_zh");
languageflag=1;
}
else
{
languageflag=0;
}
qApp->installTranslator(&translator);
retranslateStrings();
}
void maindialog::timer_deal_slot_function()
{
QDateTime datetime = QDateTime::currentDateTime();
date->setText(datetime.date().toString("yyyy-MM-dd"));
time->setText(datetime.time().toString("hh:mm:ss"));
}
#ifndef MAINDIALOG_H
#define MAINDIALOG_H
#include
class maindialog : public QDialog
{
Q_OBJECT
public:
explicit
maindialog(QWidget *parent=0);
virtual
~maindialog();
private:
QLabel
*date;
QLabel
*time;
QTimer
*timer;
QPushButton
*closeButton;
QPushButton
*switchlanguage;
int
languageflag;
void
initslot();
void
retranslateStrings();
private slots:
void timer_deal_slot_function();
void switchlanguage_clicked();
};
#endif // MAINDIALOG_H
#include "maindialog.h"
#include
int main(int argc, char *argv[])
{
QApplication
app(argc, argv);
maindialog
dialog;
dialog.show();
return
app.exec();
}
TRANSLATIONS+=switchlang_zh.ts
SOURCES += \
main.cpp
\
maindialog.cpp
HEADERS += \
maindialog.h
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
OTHER_FILES += \
switchlang_zh.qm \
switchlang_zh.ts
其中 switchlang_zh.qm 是switchlang_zh.ts
编译后生成的文件,switchlang_zh.ts
是用语言专家实现语言翻译的,qtcreator的工具->外部->Qt语言家生成switchlang_zh.ts