在 GTK+3 中,我如何获得绘图区域来响应鼠标事件?

In GTK+3, how do I get a drawingarea to respond to mouse events?

在 GTK+3 中,如何获得 drawing_area 来响应鼠标事件?

main() 函数中我声明了我的 drawing_area:

GtkWidget *drawing_area;

然后我用鼠标点击信号连接drawing_area

g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(clicked), NULL);

函数 "clicked" 定义为:

static gboolean clicked(GtkWidget *widget, GdkEventButton *event, gpointer user_data)

    printf("Clicked! \n");

    return TRUE;
}

程序运行并显示 drawing_area 但是当我点击它时,没有任何反应,没有任何反应!为什么会这样?

GtkDrawingArea 好像默认接收不到鼠标事件

看看 documentation:

To receive mouse events on a drawing area, you will need to enable them with gtk_widget_add_events(). To receive keyboard events, you will need to set the “can-focus” property on the drawing area, and you should probably draw some user-visible indication that the drawing area is focused. Use gtk_widget_has_focus() in your expose event handler to decide whether to draw the focus indicator. See gtk_render_focus() for one way to draw focus.

或尝试将事件 "button-press-event" 连接到 window:

g_signal_connect(window, "button-press-event", G_CALLBACK(clicked), NULL);

而不是

g_signal_connect(drawing_area, "button-press-event", G_CALLBACK(clicked), NULL);

如本例所示:

http://zetcode.com/gfx/cairo/basicdrawing/

一个完整的例子是: https://developer.gnome.org/gtk3/stable/ch01s05.html
这个 link 已经移动了(感谢 TrentP)。新的 link 是: https://docs.gtk.org/gtk4/getting_started.html#custom-drawing

它演示了通过 ::button-press 和 ::motion-notify 处理程序处理输入事件。