Cross-Platform GUI Programming with wxWidgets
|
To illustrate some of the concepts that we've covered, you can find a little sample in examples/chap16 on the CD-ROM. It shows some strings and a flag graphic for three languages: English, French, and German. You can change the language from the File menu, which will change the menu strings, the wxStaticText strings, and the flag graphic to suit the newly selected language. To demonstrate the different behavior of _() and wxT(), the menu help in the status line remains in English. Figure 16-2. The internationalization samples
The sample's application class contains a wxLocale pointer and a function SelectLanguage that will re-create the locale object with the appropriate language. This is the application class declaration and implementation: class MyApp : public wxApp { public: ~MyApp() ; // Initialize the application virtual bool OnInit(); // Recreates m_locale according to lang 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; }
There are two functions of particular interest in the frame class: SetupStrings and OnChangeLanguage. SetupStrings sets the labels and re-creates the menu bar, using translations for all the strings apart from the menu help strings, as follows: [View full width] void MyFrame::SetupStrings() { m_helloString->SetLabel(_("Welcome to International Sample")); m_todayString->SetLabel( wxString::Format(_("Now is %s") , wxDateTime::Now().Format()
OnChangeLanguage is called when the user wants to specify a new language, and it maps the user's selection into a locale identifier such as wxLANGUAGE_GERMAN. This identifier is passed to MyApp::SelectLanguage before SetupStrings is called to change the labels and flag bitmap. Here is the implementation of OnChangeLanguage: 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(); } }
|
|