How to get user clipboard in GTK4?

As I’ve read in docs, Gdk.ContentProvider.do_detach_clipboard(clipboard) should extract data from clipboard. But when I’m trying to do this, I have this error TypeError: Gdk.ContentProvider.detach_clipboard() takes exactly 2 arguments (1 given) (Docs says that 1 argument is needed)
https://lazka.github.io/pgi-docs/index.html#Gdk-4.0/classes/ContentProvider.html#Gdk.ContentProvider.do_detach_clipboard

def clipboard_parser(*args):
    display = Gdk.Display().get_default()
    clipboard = display.get_clipboard()
    content_provider = Gdk.ContentProvider()
    data = content_provider.do_detach_clipboard(clipboard)
    print(data)

You usually use the methods provided by Gdk.Clipboard like read_text_async(), read_texture_async() or read_value_async(). If you want to do something directly with the Gdk.ContentProvider then you can get it with get_content().

There are some examples in this tutorial: Clipboard - PyGObject.

Also remember that all methods prefixed by do_ in PyGObject are virtual methods intended to be overwritten in subclasses, see Subclassing - PyGObject.

4 Likes

On a side note, the do_ functions are virtual methods, it’s the ones to be implemented when subclassing. Usually you shall never call them directly, except when you want to chain-up the subclass implementation to the upper class, in which case it looks like:

# `do_` are static methods in Python, use `Class.virtual_method(instance, args...)`
MyContentProviderUpperClass.do_detach_clipboard(content_provider, clipboard)

That’s why you see this takes exactly 2 arguments warning.
But anyway, that’s not needed for your usecase.

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