Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get the parent GTK window from a widget?

Tags:

window

widget

gtk

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

like image 763
user631263 Avatar asked Feb 23 '11 22:02

user631263


4 Answers

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();
like image 166
bmreading Avatar answered Oct 27 '22 00:10

bmreading


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).

like image 14
Havoc P Avatar answered Oct 27 '22 00:10

Havoc P


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

like image 7
Hans-Christoph Steiner Avatar answered Oct 26 '22 23:10

Hans-Christoph Steiner


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

like image 4
serge_gubenko Avatar answered Oct 26 '22 23:10

serge_gubenko