15

I have a custom widget and it needs to launch a MessageDialog and in order for me to put that message dialog on top of the window my widget is in then I need access to the parent gtk.window. Is there a way to get the parent GTK window? Thanks

Youssef Bouhjira
  • 1,599
  • 2
  • 22
  • 38
user631263
  • 151
  • 1
  • 1
  • 3

4 Answers4

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 return the topmost widget you're inside, whether or not it's a window, thus the is_toplevel check. Yeah something is mis-named since the code above does a "get_toplevel()" then an immediate "is_toplevel()" (most likely, get_toplevel() should be called something else).

Havoc P
  • 8,365
  • 1
  • 31
  • 46
  • Gtk docs (below) seem to suggest to call `GTK_IS_WINDOW()` on the result, not `gtk_widget_is_toplevel()` https://gnome.pages.gitlab.gnome.org/gtk/gtk3/method.Widget.get_toplevel.html – Kees-Jan Jan 02 '22 at 16:24
7

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

4

Though gtk_widget_get_toplevel should work, you may also give a try to the code below. It should get the parent gtk window for the 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 this helps, regards

serge_gubenko
  • 20,186
  • 2
  • 61
  • 64
  • 4
    This takes a needless detour through low-level GDK gunge - better to stay with the GTK layer. Here you require the widget to be realized, and will likely have issues in GTK 3. – Havoc P Feb 24 '11 at 02:49
  • 1
    "though the proper recommended method should work, you might also try this needlessly complex alternative for no discernible reason"... or is there one...? – underscore_d Mar 12 '16 at 20:09
4

For GTK4, the gtk_widget_get_toplevel() method on GtkWidget has been deprecated. Instead, you can use the gtk_widget_get_root() method or the Widget:root property, which returns a GtkRoot. That GtkRoot can then be cast to a 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 in Rust

let window: Window = widget
    .root()
    .unwrap()
    .downcast::<Window>()
    .unwrap();
Brian Reading
  • 449
  • 5
  • 16