[ACCEPTED]-Can you get the parent GTK window from a widget?-gtk

Accepted answer
Score: 14

The GTK docs suggest:

   GtkWidget *toplevel = gtk_widget_get_toplevel (widget);
   if (gtk_widget_is_toplevel (toplevel))
     {
       /* Perform action on toplevel. */
     }

get_toplevel will 6 return the topmost widget you're inside, whether 5 or not it's a window, thus the is_toplevel 4 check. Yeah something is mis-named since 3 the code above does a "get_toplevel()" then 2 an immediate "is_toplevel()" (most likely, get_toplevel() should 1 be called something else).

Score: 7

In pygtk, you can get the toplevel like 1 toplevel = mywidget.get_toplevel() then feed toplevel directly to gtk.MessageDialog()

Score: 4

Though gtk_widget_get_toplevel should work, you 4 may also give a try to the code below. It 3 should get the parent gtk window for the 2 given widget and print it's title.

GdkWindow *gtk_window = gtk_widget_get_parent_window(widget);
GtkWindow *parent = NULL;
gdk_window_get_user_data(gtk_window, (gpointer *)&parent);
g_print("%s\n", gtk_window_get_title(parent));

hope 1 this helps, regards

Score: 2

For GTK4, the gtk_widget_get_toplevel() method on GtkWidget has been deprecated. Instead, you 4 can use the gtk_widget_get_root() method or the Widget:root property, which 3 returns a GtkRoot. That GtkRoot can then be cast to a 2 GtkApplicationWindow() or GtkWindow().

Here's an example in C

GtkRoot *root = gtk_widget_get_root (GTK_WIDGET (widget));
GtkWindow *window = GTK_WINDOW (root);

Here's an example 1 in Rust

let window: Window = widget
    .root()
    .unwrap()
    .downcast::<Window>()
    .unwrap();

More Related questions