Search code examples
cfunctiongtkgtk3

C: How to replace GtkAlignment function with newer GtkWidget align property


I am a new C programmer coming from Java. After reading some old books and articles, I've written the following code:

#include <gtk/gtk.h>

static void activate(GtkApplication* app, gpointer user_data) {
    GtkWidget *window;
    GtkWidget *button1;
    GtkWidget *box;

    box = gtk_alignment_new(0, 0, 0, 0);

    window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "Calculator");
    gtk_window_set_default_size(GTK_WINDOW(window), 300, 400);
    gtk_container_add(GTK_CONTAINER(window), box);

    button1 = gtk_button_new();
    gtk_button_set_label(GTK_BUTTON(button1), "1");
    gtk_widget_set_size_request(button1, 40, 30);
    gtk_container_add(GTK_CONTAINER(box), button1);

    gtk_widget_show_all(window);
}

int main(int argc, char **argv) {
    GtkApplication *app;
    int status;

    app = gtk_application_new("me.test.calculator", G_APPLICATION_FLAGS_NONE);
    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);

    return status;
}

The code compiles and runs correctly. The problem is that gtk_alignment_new is deprecated and I want to get rid of it.

I've tried replacing gtk_alignment_new with:

gtk_widget_set_halign(box, GTK_ALIGN_START);
gtk_widget_set_valign(box, GTK_ALIGN_START);

but the window does not show up when using this method. Thanks.


Solution

  • You want to set the halign/valign properties of the button (and then add the button straight into the window) to achieve the same functional results as your original code. 'box' is no longer needed at all.

    Note that a GtkWindow is a GtkBin so only takes a single child: you will need to add additional containers in between to actually make a calculator. Maybe start by adding a GtkGrid as the sole window child and then attach all your buttons into the grid.