开发者

Attaching double click event to a label

开发者 https://www.devze.com 2023-03-01 03:54 出处:网络
How开发者_StackOverflow中文版 can I attach a \"clicked\" event to a label? I tried GtkEventBox but had no luck with it.Connect to the button-press-event signal on the EventBox.Gtk# differentiates betw

How开发者_StackOverflow中文版 can I attach a "clicked" event to a label? I tried GtkEventBox but had no luck with it.


Connect to the button-press-event signal on the EventBox.


Gtk# differentiates between Widgets and 'Containers'. Most widgets placed on a Gtk# form will NOT receive mouse click events. In order to receive a mouse event you need to place the widget inside a specific container - like EventBox:

  1. Add an EventBox containter to your form. You can place it behind other Widgets or since it is not visible, unless you specifically select it to be (or change its background color).

  2. Put your label widget inside this EventBox. Notice that the label will get the shape and size of the EventBox.

  3. Add to this EventBox the signal 'ButtonPressEvent' out of the "Common Widget Signals".

If you need to identify the button that was clicked while handling this event, use the uint value in: args.Event.Button typically '1' will be the left mouse button, '2' the center button and '3' the right button ('2' might be also when both left and right buttons are clicked).


It seems you don't need EventBox at all: Since the problem is that labels don't have any associated X11 window, just give it one with set_has_window(True)! The following works for me:

    self.label = Gtk.Label()
    self.label.set_has_window(True)
    self.label.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
    self.label.connect("button-press-event", self.click_label)

The documentation says it should only be used for implementing widgets - but hey, it works. Who cares about "should"?


2019-04-17 Update:

ptomato here is right, GtkLabel is one of the exceptions that indeed requires an eventbox, so you should connect to the button-press-event signal of the eventbox. For other widgets, the set/add events APIs in my original answer should be still relevant.

Original (wrong) answer:

Connect to the button-press-event signal, but directly on the GtkLabel. I'd say you don't need an eventbox here, as GtkLabel already inherits this signal from GtkWidget. To enable the GtkLabel to receive those events, you need first to call gtk_widget_set_events or gtk_widget_add_events, and add the sensitivity to the GDK_BUTTON_PRESS_MASK event.

0

精彩评论

暂无评论...
验证码 换一张
取 消