Search code examples
clickgtkcoordinatesgtk3vala

Vala Image click event. How to get coordination of click?


I try to catch coordination of click. I created Gtk.Window, EventBox and put Image in, connected some EventButton to button_press_event and connected to this signal some method. This method try to get x and y from EventButton object but they always are 0. There is the source code:

using Gtk;
public class ComixTranslator : Window 
{
private Gtk.Image CurPage;
private Gdk.Pixbuf Canvas;
private Gtk.EventBox eventbox1;
private Gdk.EventButton ebutton1;

public bool FillDot() {
    GLib.message("pressed in %g,%g",ebutton1.x,ebutton1.y);
    return true;
}

public ComixTranslator () {
    this.title = "Image Click Sample";
    this.window_position = Gtk.WindowPosition.CENTER;
    this.destroy.connect(Gtk.main_quit);
    this.set_default_size(800,600);

    this.CurPage = new Gtk.Image();
    this.CurPage.set_from_file("test.jpg");
    this.Canvas = CurPage.pixbuf;

    this.eventbox1 = new Gtk.EventBox();
    this.eventbox1.button_press_event(ebutton1);
    this.eventbox1.button_press_event.connect(FillDot);
    this.eventbox1.add(CurPage);

    this.add(eventbox1);
}

public static int main(string[] args) {
    Gtk.init(ref args);

    ComixTranslator MainWindow = new ComixTranslator();
    MainWindow.show_all();
    Gtk.main();
    return 0;
}
}

Solution

  • You seem to be confused about how signals work—you might want to consider reading that part of the Vala Tutorial. Here is a corrected version:

    using Gtk;
    public class ComixTranslator : Window 
    {
      private Gtk.Image CurPage;
      private Gdk.Pixbuf Canvas;
      private Gtk.EventBox eventbox1;
    
      public bool FillDot(Gtk.Widget sender, Gdk.EventButton evt) {
        GLib.message("pressed in %g,%g",evt.x,evt.y);
        return true;
      }
    
      public ComixTranslator () {
        this.title = "Image Click Sample";
        this.window_position = Gtk.WindowPosition.CENTER;
        this.destroy.connect(Gtk.main_quit);
        this.set_default_size(800,600);
    
        this.CurPage = new Gtk.Image();
        this.CurPage.set_from_file("test.jpg");
        this.Canvas = CurPage.pixbuf;
    
        this.eventbox1 = new Gtk.EventBox();
        this.eventbox1.button_press_event.connect(FillDot);
        this.eventbox1.add(CurPage);
    
        this.add(eventbox1);
      }
    
      public static int main(string[] args) {
        Gtk.init(ref args);
    
        ComixTranslator MainWindow = new ComixTranslator();
        MainWindow.show_all();
        Gtk.main();
        return 0;
      }
    }
    

    Notice that the callback accepts the Gdk.EventButton as an argument. In your code, you have this.eventbox1.button_press_event(ebutton1);, which will emit the button_press_event signal with the data from ebutton1 as its argument.