16.6 一个小例子
为了演示本章介绍的这些内容,随书光盘上examples/chap16目录中举了一个小例子.它以三种语言显示了一些字符串和图片:英语,法语和德语. 你可以从文件菜单更改当前的语言,这将导致菜单字符串,静态文本控件和使用的图片作出相应的改变.为了演示_()宏和wxT()的区别,状态栏的字符串始 终保持英语不变.
这个例子的应用程序类包含一个指向wxLocale类型的指针和一个函数SelectLanguage用来更改当前的语言.主要的声明和实现如下:
class MyApp : public wxApp
{
public:
~MyApp() ;
// 初始化应用程序
virtual bool OnInit();
// 根据用户选择的语言重新创建wxLocale变量
void SelectLanguage(int lang);
private:
wxLocale* m_locale; // 'our' locale
};
IMPLEMENT_APP(MyApp)
bool MyApp::OnInit()
{
wxImage::AddHandler( new wxPNGHandler );
m_locale = NULL;
SelectLanguage( wxLANGUAGE_DEFAULT );
MyFrame *frame = new MyFrame(_("i18n wxWidgets App"));
frame->Show(true);
return true;
}
void MyApp::SelectLanguage(int lang)
{
delete m_locale;
m_locale = new wxLocale( lang );
m_locale->AddCatalog( wxT("i18n") );
}
MyApp::~MyApp()
{
delete m_locale;
}
主窗口的两个函数SetupStrings和OnChangeLanguage可能是你最感兴趣的部分,SetupStrings更改相关控件的字符串并且重新创建菜单条,以便演示更改wxLocale以后相关字符串的翻译:
void MyFrame::SetupStrings()
{
m_helloString->SetLabel(_("Welcome to International Sample"));
m_todayString->SetLabel( wxString::Format(_("Now is %s") , wxDateTime::Now().Format()
.c_str() ) );
m_thousandString->SetLabel( wxString::Format(_("12345 divided by 10 is written as %
.1f") , 1234.5 ) );
m_flag->SetBitmap(wxBitmap( _("flag.png") , wxBITMAP_TYPE_PNG ));
// 创建菜单条
wxMenu *menuFile = new wxMenu;
// About菜单应该位于帮助菜单
wxMenu *helpMenu = new wxMenu;
helpMenu->Append(wxID_ABOUT, _("&About...\tF1"),
wxT("Show about dialog"));
menuFile->Append(wxID_NEW, _("Change language..."),
wxT("Select a new language"));
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT, _("E&xit\tAlt-X"),
wxT("Quit this program"));
wxMenuBar *menuBar = new wxMenuBar();
menuBar->Append(menuFile, _("&File"));
menuBar->Append(helpMenu, _("&Help"));
wxMenuBar* formerMenuBar = GetMenuBar();
SetMenuBar(menuBar);
delete formerMenuBar;
SetStatusText(_("Welcome to wxWidgets!"));
}
OnChangeLanguage在用户更改当前语言的时候被调用,它将用户的选择映射到某种语言标识(比如 wxLANGUAGE_GERMAN)上.这个标识被传递给MyApp::SelectLanguage以便设置当前的locale,然后调用 SetupStrings根据设置的locale更改当前的字符串和图片,如下所示:
void MyFrame::OnChangeLanguage(wxCommandEvent& event)
{
wxArrayInt languageCodes;
wxArrayString languageNames;
languageCodes.Add(wxLANGUAGE_GERMAN);
languageNames.Add(_("German"));
languageCodes.Add(wxLANGUAGE_FRENCH);
languageNames.Add(_("French"));
languageCodes.Add(wxLANGUAGE_ENGLISH);
languageNames.Add(_("English"));
int lang = wxGetSingleChoiceIndex( _("Select language:"),
_("Language"), languageNames );
if ( lang != -1 )
{
wxGetApp().SelectLanguage(languageCodes[lang]);
SetupStrings();
}
}