4c. wxWidgets – Toolbar

OVERVIEW

Toolbars are a band of icons, with or without text which span across the length or breadth of a window. They can contain controls like labels or dropdowns and they can be dockable. Here we look at how to make a single toolbar with icons and handle clicks on the icons. The icons are generated from PNG files. In the sample code, we let wxWidgets size the icons as required, but otherwise you can set the size of the icons also.

SAMPLE CODE

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

class Toolbar: public wxFrame {

	public:
		Toolbar(const wxString& title);
		void OnToolItem(wxCommandEvent &evt);

};

const int ID_NEW = 101;
const int ID_SAVE = 102;
const int ID_OPEN = 103;
const int ID_EXPORT = 104;


toolbars.cpp
#include "toolbars.h"

Toolbar::Toolbar(const wxString& title):
	wxFrame(NULL, -1, title, wxDefaultPosition, wxSize(500,300)) {

	SetBackgroundColour(wxColour(255,100,200));
	wxImage::AddHandler(new wxPNGHandler());	
	wxBitmap bmpAdd (wxT("bulb.png"), wxBITMAP_TYPE_PNG);
	wxBitmap bmpSave (wxT("folder.png"), wxBITMAP_TYPE_PNG);
	wxBitmap bmpOpen (wxT("edit.png"), wxBITMAP_TYPE_PNG);
	wxBitmap bmpExport (wxT("export.png"), wxBITMAP_TYPE_PNG);
	
	wxToolBar *tbr = CreateToolBar();
	tbr->AddTool(ID_NEW, wxT("Add"), bmpAdd);
	tbr->AddTool(ID_SAVE, wxT("Save"), bmpSave);
	tbr->AddTool(ID_OPEN, wxT("Open"), bmpOpen);
	tbr->AddSeparator();
	tbr->AddTool(ID_EXPORT, wxT("Export"), bmpExport);

	tbr->Realize();

	tbr->Bind(wxEVT_TOOL, &Toolbar::OnToolItem, this);

}

void Toolbar::OnToolItem(wxCommandEvent &evt) {

	int eventId= evt.GetId();
	wxString strId = wxT("");
	strId = wxString::Format(wxT("%d"), evt.GetId());
	wxPuts(strId);
	if (eventId == ID_NEW) 
		wxLogMessage("New file item");
	else if (eventId == ID_SAVE )
		wxLogMessage("Save file item");
	else if (eventId == ID_OPEN) 
		wxLogMessage("Open file item");
	else if (eventId == ID_EXPORT) 
		wxLogMessage("Export file item");

	else if (eventId == wxID_EXIT)
		Close(true);
}



The output is given below

The icons used here are provided below for download.

1 Trackback / Pingback

  1. 1.wxWidgets – Introduction – Truelogic Blog

Leave a Reply

Your email address will not be published.


*