The wxUpdateUIEvent event
Introduction
The wxUpdateUIEvent (wxWidgets: wxUpdateUIEvent Class Reference) class is used to give widgets the opportunity to update their state. A common use case would be a menu item that needs to be enabled or disabled based on some condition. The menu item can register a handler for the wxUpdateUIEvent event and in that handler check the condition and enable or disable itself.
Example
The full source for this example is available from our GitHub repository: wxWidgetsTutorials/Events/UpdateUIEvent1.
#ifndef _TUTORIALS_WXWIDGETS_UPDATEUIEVENT1FRAME_H_ #define _TUTORIALS_WXWIDGETS_UPDATEUIEVENT1FRAME_H_ #include <wx/frame.h> #include <wx/checkbox.h> class UpdateUIEvent1Frame : public wxFrame { public: UpdateUIEvent1Frame(const wxString& title); private: void OnExit(wxCommandEvent& event); void OnExitUpdate(wxUpdateUIEvent& evt); private: wxCheckBox* m_checkbox; wxDECLARE_EVENT_TABLE(); }; #endif
#include "UpdateUIEvent1Frame.h" #include <wx/menu.h> #include <wx/panel.h> UpdateUIEvent1Frame::UpdateUIEvent1Frame(const wxString& title) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, wxSize(250, 150)), m_checkbox(0) { wxMenuBar* menuBar = new wxMenuBar; wxMenu* menuFile = new wxMenu; menuFile->Append(wxID_EXIT); menuBar->Append(menuFile, "&File"); SetMenuBar(menuBar); // Add a checkbox that will determine // whether the Exit menu is enabled or not wxPanel* panel = new wxPanel(this); panel->SetBackgroundColour(*wxWHITE); m_checkbox = new wxCheckBox(panel, wxID_ANY, "Enable Exit menu", wxPoint(50, 30)); } void UpdateUIEvent1Frame::OnExit(wxCommandEvent& event) { Close(true); } void UpdateUIEvent1Frame::OnExitUpdate(wxUpdateUIEvent& evt) { evt.Enable(m_checkbox->GetValue()); } wxBEGIN_EVENT_TABLE(UpdateUIEvent1Frame, wxFrame) EVT_MENU(wxID_EXIT, UpdateUIEvent1Frame::OnExit) EVT_UPDATE_UI(wxID_EXIT, UpdateUIEvent1Frame::OnExitUpdate) wxEND_EVENT_TABLE()
The rest of the files don't have any significant changes but are shown here for completeness.
#ifndef _TUTORIALS_WXWIDGETS_UPDATEUIEVENT1APP_H_ #define _TUTORIALS_WXWIDGETS_UPDATEUIEVENT1APP_H_ #include <wx/app.h> class UpdateUIEvent1App : public wxApp { public: virtual bool OnInit(); }; #endif
#include "UpdateUIEvent1App.h" #include "UpdateUIEvent1Frame.h" wxIMPLEMENT_APP(UpdateUIEvent1App); bool UpdateUIEvent1App::OnInit() { UpdateUIEvent1Frame* frame = new UpdateUIEvent1Frame("UpdateUIEvent1"); frame->Show(true); return true; }