Drag & dropping files with GTK4

Hello!

I’m porting a Python app from GTK3 to GTK4, and I have trouble reimplementing dropping multiple files from the file manager.

I tried using a Gtk.DropTarget and if I set its gtypes to Gio.File, I get a file, but I can’t get multiple files.

I also tried using a Gtk.DropTargetAsync with text/uri-list in its formats, but reading its result after the drop crashes the app, I’m not sure if my code is wrong or if it’s a bug in the bindings (see sample code below).

So what would be the best way to implement it?

Also, is there a way to get drag and drop between apps working in a Flatpak? I read here that it is built into GTK4, is there anything special to do to make it work?

Sample code using Gtk.DropTargetAsync
def _on_drop(
    self,
    widget: Gtk.DropTarget,
    drop: Gdk.Drop,
    x: int,
    y: int
):
    def _drop_read_async(drop: Gdk.Drop, result: Gio.AsyncResult):
        value = drop.read_finish(result)  # Crashes here
        print(value)

    drop.read_async(
        ['text/uri-list'],
        GLib.PRIORITY_DEFAULT,
        None,
        _drop_read_async
    )
    drop.finish(Gdk.DragAction.COPY)

drop_target = Gtk.DropTargetAsync(
    actions=Gdk.DragAction.COPY,
    formats=Gdk.ContentFormats.new(['text/uri-list'])
)
window.add_controller(drop_target)
drop_target.connect("drop", _on_drop)

For a list of files, you want to use GDK_TYPE_FILE_LIST.

We don’t have good documentation for this, but it is just a GSlist of GFile objects, wraped in a boxed type.

1 Like

Thank you @matthiasc , using Gdk.FileList in the gtypes lets me drop multiple files, and I get a Gdk.FileList.

However, I don’t know what to do with it. If it is just a GSlist, I guess the Python binding should have converted it into a Python list, but using dir() on it doesn’t show any useful method and I can’t iterate over it.

Is there anything else I need to do, or are the bindings lacking the implementation?

1 Like

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