程序运行时改变语言

程序很简单,就不解释了,呵呵


//tqt.h
#ifndef TQT_H_
#define TQT_H_

#include <QtGui>
#include <QtCore>

//QT动态加载(运行时改变)语言的例子
class Dialog : public QDialog
{
	Q_OBJECT
private:
	QLabel *textLabel;
	QLabel *languageLabel;
	QComboBox *comboBox;
	QMap<QString, QString> translatorMap;
	QTranslator translator;
	//由翻译文件的文件名得到语言的名字
	QString LanguageName(const QString &name);

public:
	Dialog(QDialog *parent = 0);
	~Dialog();
	void SetLanguageCombo();
	//改变语言
	void ChangeLanguage(const QString &language);
	//语言加载完成名刷新界面
	void Reflush();

	public slots:
		void ChooseLanguage(const QString &language);
};

#endif



//tqt.cpp
#include "tqt.h"

Dialog::Dialog(QDialog *parent /* = 0 */)
{
	setWindowTitle( tr("English") );
	resize(200, 200);

	textLabel = new QLabel(tr("I am Chinese"), this);
	languageLabel = new QLabel(tr("Language:"), this);
	comboBox = new QComboBox(this);
	QHBoxLayout *subLayout = new QHBoxLayout;
	subLayout->addWidget(languageLabel);
	subLayout->addWidget(comboBox);
	QVBoxLayout *layout = new QVBoxLayout;
	layout->addWidget(textLabel);
	layout->addLayout(subLayout);
	setLayout(layout);
	SetLanguageCombo();
	connect(comboBox, SIGNAL(activated(const QString&)),
		this, SLOT(ChooseLanguage(const QString&)));
}

Dialog::~Dialog()
{

}

QString Dialog::LanguageName(const QString &name)
{
	QTranslator translator;
	translator.load(name);
	QString str = translator.translate("Dialog", "English");
	return str;
}

void Dialog::SetLanguageCombo()
{
	comboBox->addItem("English");
	//所有语言包(*.qm)都放在"language"这个文件夹下
	QDir dir("language");
	QStringList fileNames = dir.entryList(QStringList("*.qm"),
		QDir::Files, QDir::Name);
	QString name;

	QStringList::iterator iter = fileNames.begin();
	for(; iter!=fileNames.end(); ++iter)
	{
		
		*iter = dir.filePath(*iter);
		name = *iter;
		name = LanguageName(*iter);
		translatorMap.insert(name, *iter);
		comboBox->addItem(name);
	}
}

void Dialog::ChooseLanguage(const QString &language)
{
	int index = comboBox->currentIndex();
	ChangeLanguage(language);
}

void Dialog::ChangeLanguage(const QString &language)
{
	if("English" == language)
		qApp->removeTranslator(&translator);
	else
	{
		QString fileName = translatorMap.value(language);
		translator.load(fileName);
		qApp->installTranslator(&translator);
	}
	Reflush();
}

void Dialog::Reflush()
{
	setWindowTitle( tr("English") );
	textLabel->setText( tr("I am Chinese") );
	languageLabel->setText( tr("Language:") );
}



//main.cpp
#include "tqt.h"

int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	Dialog *dialog = new Dialog;
	dialog->show();
	return app.exec();
}



你可能感兴趣的:(程序运行时改变语言)