Skip to content

Instantly share code, notes, and snippets.

@crab2313
Last active November 10, 2022 09:16
Show Gist options
  • Save crab2313/9b1087677388e4d9156b5668b1794349 to your computer and use it in GitHub Desktop.
Save crab2313/9b1087677388e4d9156b5668b1794349 to your computer and use it in GitHub Desktop.
Re-positioning Gtk widget with a mouse drag in Python (GTK4 version)
#!/usr/bin/env python
import sys, gi, operator
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, Gdk
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_default_size(600, 400)
self.set_title("Test Drag & Drop")
self.fixed = Gtk.Fixed()
self.set_child(self.fixed)
self.image = Gtk.Image.new_from_icon_name('window-close-symbolic')
self.image.set_pixel_size(64)
self.fixed.put(self.image, 0, 0)
controller = Gtk.GestureDrag()
controller.connect('drag-begin', self.on_begin)
controller.connect('drag-update', self.on_update)
self.image.add_controller(controller)
def on_begin(self, controller, start_x, start_y):
self.diff = tuple(map(operator.sub, self.fixed.get_child_position(self.image), self.get_fixed_pos()))
def on_update(self, controller, offset_x, offset_y):
move = map(operator.add, self.get_fixed_pos(), self.diff)
# bounding the movable widget inside the GtkFixed container
max_width = self.fixed.get_width() - self.image.get_width()
max_height = self.fixed.get_height() - self.image.get_height()
move_x, move_y = map(min, (max_width, max_height), map(max, (0, 0), move))
self.fixed.move(self.image, move_x, move_y)
def get_fixed_pos(self):
pointer = self.get_display().get_default_seat().get_pointer()
_, px, py, _ = self.fixed.get_native().get_surface().get_device_position(pointer)
return self.translate_coordinates(self.fixed, px, py)
class MyApp(Adw.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.connect('activate', self.on_activate)
def on_activate(self, app):
self.win = MainWindow(application=app)
self.win.present()
app = MyApp(application_id="com.example.GtkApplication")
app.run(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment