8c.wxWidgets – wxToggleButton

OVERVIEW

wxToggleButtons are like checkboxes in that they represent two states- true or false. Except here, they generate a command event every time since they are buttons.

The sample code below shows 3 toggle buttons and a label which shows the state of the each of the 3 toggle buttons.

SAMPLE CODE

togglebutton.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif
#include <wx/tglbtn.h>

class ToggleButton: public wxFrame {

    public:
      ToggleButton(const wxString &title);
      void onClick(wxCommandEvent &event);

    private:
      wxToggleButton *mBtn1, *mBtn2, *mBtn3;
      wxStaticText *mLbl;

};


togglebutton.cpp
#include "togglebutton.h"


ToggleButton::ToggleButton(const wxString &title):

    wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,200)) {
 
    wxPanel *panel = new wxPanel(this, -1);    
    wxBoxSizer *vbox = new wxBoxSizer(wxVERTICAL);
    panel->SetSizer(vbox);

    mBtn1 = new wxToggleButton(panel, -1, wxString("1"));
    mBtn2 = new wxToggleButton(panel, -1, wxString("2"));
    mBtn3 = new wxToggleButton(panel, -1, wxString("3"));
    mLbl = new wxStaticText(panel, -1, wxString(""));

    vbox->Add(mBtn1, 1, wxEXPAND);
    vbox->Add(mBtn2, 1, wxEXPAND);
    vbox->Add(mBtn3, 1, wxEXPAND);
    vbox->Add(mLbl, 1, wxEXPAND);

    mBtn1->Bind(wxEVT_TOGGLEBUTTON, &ToggleButton::onClick, this);
    mBtn2->Bind(wxEVT_TOGGLEBUTTON, &ToggleButton::onClick, this);
    mBtn3->Bind(wxEVT_TOGGLEBUTTON, &ToggleButton::onClick, this);
    Center();

}

void ToggleButton::onClick(wxCommandEvent &event) {
	wxString label = wxT("");
	if (mBtn1->GetValue())
		label.Append("1=toggled ");
	if (mBtn2->GetValue())
		label.Append("2=toggled ");
	if (mBtn3->GetValue())
		label.Append("3=toggled ");
		
 	mLbl->SetLabel(label);	
}




main.h
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class Main: public wxApp {

	public:
	        virtual bool OnInit();
};

main.cpp
#include "main.h"
#include "togglebutton.h"
 
IMPLEMENT_APP(Main)

bool Main::OnInit() {

    ToggleButton *app = new ToggleButton(wxT("ToggleButton"));
    app->Show(true);
}

The output is shown below

Be the first to comment

Leave a Reply

Your email address will not be published.


*