1 #include <gtk/gtk.h>
2
3
4
5 /* This is the callback function.
6 * It is a handler function which reacts to the signal.
7 * In this case, it will notify the user the value of their spinbutton
8 * as a label.
9 */
10 static void
spin_clicked(GtkSpinButton * spinbutton,gpointer user_data)11 spin_clicked (GtkSpinButton *spinbutton,
12 gpointer user_data)
13 {
14 GtkWidget *label = user_data;
15 gint value = gtk_spin_button_get_value_as_int (spinbutton);
16
17 /* %d - Is used when printing integers.
18 * Note: Using g_strdup_printf returns a string that must be freed.
19 * (In which is done below)
20 */
21 gchar *str = g_strdup_printf ("The number you selected is %d.", value);
22 gtk_label_set_text (GTK_LABEL (label), str);
23
24 g_free(str);
25 }
26
27
28
29 static void
activate(GtkApplication * app,gpointer user_data)30 activate (GtkApplication *app,
31 gpointer user_data)
32 {
33 /* Declare variables */
34 GtkWidget *window;
35 GtkWidget *label;
36 GtkWidget *grid;
37 GtkWidget *spin_button;
38 GtkAdjustment *adjustment;
39
40
41 /* Create a window with a title, a border width, and a default size */
42 window = gtk_application_window_new (app);
43 gtk_window_set_title (GTK_WINDOW (window), "SpinButton Example");
44 gtk_window_set_default_size (GTK_WINDOW (window), 210, 70);
45 gtk_container_set_border_width (GTK_CONTAINER (window), 5);
46
47 /* Create a label to be shown in the window */
48 label = gtk_label_new ("Choose a number");
49
50 /* Create an adjustment representing an adjustable bounded value */
51 adjustment = gtk_adjustment_new (0, 0, 100, 1, 0, 0);
52
53
54 /* Create a spin button that is to be as wide as possible */
55 spin_button = gtk_spin_button_new (adjustment, 1, 0);
56 gtk_widget_set_hexpand (spin_button, TRUE);
57
58 /* Connecting the "value-changed" signal for the spinbutton
59 * to the appropriate callback function.
60 */
61 g_signal_connect (spin_button,
62 "value-changed",
63 G_CALLBACK (spin_clicked),
64 label);
65
66
67 /* Create a grid and arrange everything accordingly */
68 grid = gtk_grid_new ();
69 gtk_grid_set_column_spacing (GTK_GRID (grid), 10);
70 gtk_grid_set_column_homogeneous (GTK_GRID (grid), TRUE);
71 gtk_grid_attach (GTK_GRID (grid), spin_button, 0, 0, 1, 1);
72 gtk_grid_attach (GTK_GRID (grid), label, 0, 1, 1, 1);
73
74
75 gtk_container_add (GTK_CONTAINER (window), grid);
76
77 gtk_widget_show_all (window);
78 }
79
80
81
82 int
main(int argc,char ** argv)83 main (int argc, char **argv)
84 {
85 GtkApplication *app;
86 int status;
87
88 app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
89 g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
90 status = g_application_run (G_APPLICATION (app), argc, argv);
91 g_object_unref (app);
92
93 return status;
94 }
95