gtkmm – example 2

This is part of a more general work dedicated to gtkmm accessible here. This example shows how to create a container (Gtk::Grid) and place buttons inside:

capture

Download

Source code

main.cpp

#include <mainwindow.h>
#include <gtkmm.h>

int main(int argc, char* argv[])
{
	// Initialize gtkmm
	Gtk::Main app(argc, argv);
	// Create the window
	mainwindow w;
	// Start main loop
	Gtk::Main::run(w);
	return 0;
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <gtkmm/button.h>
#include <gtkmm/window.h>
#include <gtkmm/grid.h>


// The class mainwindow inherits from Gtk::Window
class mainwindow : public Gtk::Window
{
	// Constructor and destructor
public:    
	mainwindow();
	virtual             ~mainwindow();

protected:
	//Signal handlers (run when the button are clicked)
	void                  on_button_1();
	void                  on_button_2();

	//Member widgets:
	Gtk::Button           button1;
	Gtk::Button           button2;
	Gtk::Grid             mainGrid;
};


#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include <iostream>


// Constructor of the main Window (build ui interface).
mainwindow::mainwindow()
{
	// Initialize the main window
	set_border_width(10);

	// Create the first button
	button1.add_label("Button 1");
	button1.signal_clicked().connect(sigc::mem_fun(*this,&mainwindow::on_button_1));
	mainGrid.add(button1);

	// Create the second button
	button2.add_label("Button 2");
	button2.signal_clicked().connect(sigc::mem_fun(*this,&mainwindow::on_button_2));
	mainGrid.add(button2);

	// Display the main grid in the main window
	mainGrid.show_all();
	add(mainGrid);
}


// Destructor of the class
mainwindow::~mainwindow()
{}


// Call when the first button is clicked
void mainwindow::on_button_1()
{
	std::cout << "Button 1" << std::endl;
}


// Call when the second button is clicked
void mainwindow::on_button_2()
{
	std::cout << "Button 2" << std::endl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *