Created
March 6, 2023 23:35
-
-
Save angstyloop/0cc16a3dedc9a8019f09e2868ada6bca to your computer and use it in GitHub Desktop.
Simple GTK 3 example of how to use GtkScale (which inherits from GtkRange) in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** scale.c | |
* | |
* GTK3 example of how to use GtkScale (which inherits from GtkRange). | |
* | |
* COMPILE | |
* gcc -Wall -o scale scale.c `pkg-config --libs --cflags gtk+-3.0` | |
* | |
* EXAMPLE | |
* ./scale | |
* | |
*/ | |
#include <gtk/gtk.h> | |
void value_changed(GtkRange*, gpointer); | |
int main(int argc, char** argv) { | |
// Initialize GTK | |
gtk_init(&argc, &argv); | |
// Create the window | |
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); | |
gtk_window_set_default_size(GTK_WINDOW(window), 250, 50); | |
gtk_window_set_resizable (GTK_WINDOW(window), FALSE); | |
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); | |
// Create the root widget, which contains all the other widgets | |
GtkWidget* root = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 20); | |
// Create the scale widget, a type of range widget. | |
GtkWidget* scale = | |
gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, 100, 1); | |
gtk_scale_set_draw_value(GTK_SCALE(scale), FALSE); | |
gtk_widget_set_size_request(scale, 150, -1); | |
// Create label to show current value | |
GtkWidget* label = gtk_label_new("0"); | |
// Pack the scale widget and label into the root widget | |
gtk_box_pack_start(GTK_BOX(root), scale, FALSE, FALSE, 0); | |
gtk_box_pack_start(GTK_BOX(root), label, FALSE, FALSE, 20); | |
// Add the root widget to the window | |
gtk_container_add(GTK_CONTAINER(window), root); | |
// Connect signal handlers | |
g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); | |
g_signal_connect(scale, "value-changed", G_CALLBACK(value_changed), label); | |
// Show the window | |
gtk_widget_show_all(window); | |
// Start the GTK main loop | |
gtk_main(); | |
return EXIT_SUCCESS; | |
} | |
static gchar label_text[4] = {0}; | |
void value_changed(GtkRange* range, gpointer window) { | |
guint8 value = gtk_range_get_value(range); | |
value = value < 0 ? 0 : value > 100 ? 100 : value; | |
snprintf(label_text, 4, "%d", value); | |
gtk_label_set_text(GTK_LABEL(window), label_text); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment