- Prison Code Breaker Diary -

=> aka: Nhật Kí Code Tù

Categories

Have you done practice GtkWindow and GtkLabel well?
Now, it's time to introduce new widget: GtkButton, simply a button, which can be pressed in order to do something. This is a very common widget used in every application.

First thing first, you need to look over the reference for GtkButton: GtkButton Reference

Practice 1: Create a button on a window labeled as "Exit", the button-clicking event will exit program.


#include <gtk/gtk.h>

int
main( int argc, char *argv[] )
{
GtkWidget *window;
GtkWidget *button;

gtk_init( &argc, &argv );

window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
gtk_window_set_title( GTK_WINDOW( window ), "[JaPh]Lesson 3: GtkButton" );
gtk_widget_set_size_request( window, 50, 50 );

// create a new button with label: Exit
button = gtk_button_new_with_label( "Exit" );

// if you want to use combination with Alt + X
//button = gtk_button_new_with_mnemonic( "E_xit" );

// add button to main window
gtk_container_add( GTK_CONTAINER( window ), button );

g_signal_connect( G_OBJECT(window), "destroy", G_CALLBACK( gtk_main_quit ), NULL );
// connect button click event
g_signal_connect( G_OBJECT(button), "clicked", G_CALLBACK( gtk_main_quit ), NULL );

gtk_widget_show_all( window );

gtk_main( );

return 0;
}


Practice 2: Click a button will increase a count value by 1, if the count value is divisible by 3, then exit immediately.


#include <gtk/gtk.h>
#include <glib.h>

static gint count = 0;

void
btn_count_clicked_event( GtkButton *button, gpointer p )
{
++count;
g_print("Count = %d\n", count );
if( count % 3 == 0) {
g_print("Exit\n");
gtk_main_quit( );
}
}

int
main( int argc, char *argv[] )
{
GtkWidget *window;
GtkWidget *btn_count;

gtk_init( &argc, &argv );

window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
gtk_window_set_title( GTK_WINDOW( window ), "[JaPh]Lesson 3: GtkButton" );
gtk_widget_set_size_request( window, 100, 50 );

btn_count = gtk_button_new_with_mnemonic(" C_ount ");

gtk_container_add( GTK_CONTAINER( window ), btn_count );

g_signal_connect( G_OBJECT( window ), "destroy", G_CALLBACK( gtk_main_quit), NULL );
g_signal_connect( G_OBJECT( btn_count ), "clicked", G_CALLBACK( btn_count_clicked_event ), NULL );

gtk_widget_show_all( window );

gtk_main( );

return 0;
}

GtkButton is a quite very easy widget, so you just need to practice for a while.

The next tutorial lesson will talk about container classes, GtkContainer.

Keep on practice w/ Gtk+ programming everyday, ok?

Have fun!@

0 comments

Post a Comment