Set absolut window position in gtk4

I read that this functionality was moved to X11 as a specific functionality. Can you tell me how to move the window to a specific position (in pixels) in GTK 4?

You will need to get the GdkSurface of the window you want to move, using gtk_native_get_surface(). Then you will need to get the XID out of that surface, using gdk_x11_surface_get_xid(). After that, you can use XMoveWindow(). Since XMoveWindow() also needs a Display, you’ll have to get the GdkDisplay using gtk_widget_get_display(), and call gdk_x11_display_get_xdisplay() to retrieve the X11 display connection.

2 Likes

@Murloc look at my recent post, I just figured the same calls out and shared my code along with a related question – but that seam answered now by Bassi above:

Example code to set and get window position and size.

1 Like

can you explain why gtk_native_get_surface return NULL? And the code suggested by pyzahl crashes with a segmentation fault
i try this simple code:

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <gdk/x11/gdkx.h>
#include <X11/Xlib.h>

static void on_activate (GtkApplication *app) {
  GtkWidget *window = gtk_application_window_new (app);
  GdkSurface* native = gtk_native_get_surface(GTK_NATIVE (window));
  printf("%p\n",native); //print (nil)
  Window   xw = gdk_x11_surface_get_xid(GDK_SURFACE (gtk_native_get_surface(GTK_NATIVE (window))));
  Display *xd = gdk_x11_display_get_xdisplay(GDK_SURFACE (gtk_native_get_surface(GTK_NATIVE (window))));
  XMoveWindow (xd, xw, 100, 100);
  gtk_window_present (GTK_WINDOW (window));
}

int main (int argc, char *argv[]) {
  GtkApplication *app = gtk_application_new ("com.example.GtkApplication",
                                         G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (on_activate), NULL);
  return g_application_run (G_APPLICATION (app), argc, argv);
}

GtkWindows don’t have an associated surface until they are realized. Likely you want to put that code in a realize signal handler for the window, or at least call it after gtk_window_present.

2 Likes

and the code to get the X11 display should be like this.

Display *xd = gdk_x11_display_get_xdisplay(gtk_widget_get_display(window));

Right, I use this code to move and position windows after they are display, and yes the user can see the initial placement and the following move. Looks like a bit magic but fine for me.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.