Create the Main Function and UI Elements
Now, let's create the main
function and set up the user interface.
int main(int argc, char *argv[]) {
GtkWidget *window;
GtkWidget *grid;
GtkWidget *start_stop_button;
GtkWidget *reset_button;
gtk_init(&argc, &argv); // Initialize GTK
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "Stopwatch"); // Set the window title
gtk_window_set_default_size(GTK_WINDOW(window), 200, 200); // Set the default window size
g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); // Connect the window close event
grid = gtk_grid_new(); // Create a grid layout
gtk_container_add(GTK_CONTAINER(window), grid); // Add the grid to the window
label = gtk_label_new("00:00"); // Create a GTK label initially displaying "00:00"
gtk_widget_set_hexpand(label, TRUE); // Allow the label to expand horizontally
gtk_widget_set_vexpand(label, TRUE); // Allow the label to expand vertically
gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1); // Add the label to the grid
start_stop_button = gtk_button_new_with_label("Start"); // Create a button with the label "Start"
gtk_widget_set_hexpand(start_stop_button, TRUE); // Allow the button to expand horizontally
gtk_widget_set_vexpand(start_stop_button, TRUE); // Allow the button to expand vertically
g_signal_connect(G_OBJECT(start_stop_button), "clicked", G_CALLBACK(start_stop_button_clicked), NULL); // Connect the button click event
gtk_grid_attach(GTK_GRID(grid), start_stop_button, 0, 1, 1, 1); // Add the button to the grid
reset_button = gtk_button_new_with_label("Reset"); // Create a button with the label "Reset"
gtk_widget_set_hexpand(reset_button, TRUE); // Allow the button to expand horizontally
gtk_widget_set_vexpand(reset_button, TRUE); // Allow the button to expand vertically
g_signal_connect(G_OBJECT(reset_button), "clicked", G_CALLBACK(reset_button_clicked), NULL); // Connect the button click event
gtk_grid_attach(GTK_GRID(grid), reset_button, 0, 2, 1, 1); // Add the button to the grid
gtk_widget_show_all(window); // Show the window and all its child widgets
timer_id = g_timeout_add(1000, timer_callback, NULL); // Create a timer that triggers every 1000 ms (1 second) and calls timer_callback
gtk_main(); // Start the GTK main event loop
return 0;
}
- The
main
function sets up the GTK window, labels, buttons, and their click event handlers.