Search code examples
gtk3

Alternative to deprecated gtk_alignment_new


I used the GtkAlignment widget to control the alignment and size of its child widget. But gtk_alignment_new has been deprecated since version 3.14 and should not be used in newly-written code. What functions should I use as alternatives to let the code be gtk3+ compatible?

#include <gtk/gtk.h>

int main(int argc, char *argv[]) {

  GtkWidget *window;
  GtkWidget *button;
  GtkWidget *halign;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "Tooltip");
  gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
  gtk_container_set_border_width(GTK_CONTAINER(window), 15);

  button = gtk_button_new_with_label("Button");
  gtk_widget_set_tooltip_text(button, "Button widget");

  halign = gtk_alignment_new(0, 0, 0, 0);
  gtk_container_add(GTK_CONTAINER(halign), button);
  gtk_container_add(GTK_CONTAINER(window), halign);  

  gtk_widget_show_all(window);

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

  gtk_main();

  return 0;
}

Solution

  • As suggested in the comment, use these two functions instead:

    • void gtk_widget_set_halign (GtkWidget *widget, GtkAlign align); Sets the horizontal alignment of widget.

    • gtk_widget_get_valign (GtkWidget *widget); Sets the vertical alignment of widget.

    The enum GtkAlign types are the following:

    • GTK_ALIGN_START: The 'start' of the layout. Vertically this is the top, horizontally this is left/right according to LTR/RTL

    • GTK_ALIGN_END: Opposite of GTK_ALIGN_START

    • GTK_ALIGN_CENTER: The middle of the layout

    • GTK_ALIGN_FILL : Take all available space

    for scaling use GTK_ALIGN_FILL.

    So the gtk3+ compatible alternative for your code is the following:

    #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), "Tooltip");
      gtk_window_set_default_size(GTK_WINDOW(window), 300, 200);
    
      gtk_container_set_border_width(GTK_CONTAINER(window), 15);
    
      button = gtk_button_new_with_label("Button");
      gtk_widget_set_tooltip_text(button, "Button widget");
    
      gtk_widget_set_halign (button, GTK_ALIGN_START);
      gtk_widget_set_valign (button, GTK_ALIGN_START);
    
      gtk_container_add (GTK_CONTAINER (window), button);
      g_signal_connect(G_OBJECT(window), "destroy",
          G_CALLBACK(gtk_main_quit), NULL);
      gtk_widget_show_all(window);
      gtk_main();
    
      return 0;
    }