Search code examples
pythongtk

Is it possible to get cursor coordinates in textview gtk


I am working on an app with Gtk using Pythons gi.repository. I would like to know if there it is possible to get the coordinates of the cursor relative to the screen any time it is moved in the text view.

e.g. it returns x1, x2, y1, y2 of the cursor.


Solution

  • Yes, it is possible. Just bind the TextView to "event", and in the handler function, check if the event type is Gdk.EventType.MOTION_NOTIFY.

    import gi
    
    gi.require_version("Gdk", "3.0")
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gdk, Gtk
    
    win = Gtk.Window()
    
    def on_event(widget, event):
        # Check if the event is a mouse movement
        if event.type == Gdk.EventType.MOTION_NOTIFY:
            print(event.x, event.y) # Print the mouse's position in the window
    
    t = Gtk.TextView()
    t.connect("event", on_event)
    win.add(t)
    
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()