10.1. The EventBox
Some GTK widgets don't have associated X
windows, so they just draw on their parents. Because of this, they cannot
receive events and if they are incorrectly sized, they don't clip so you
can get messy overwriting, etc. If you require more from these widgets,
the EventBox is for you.
At first glance, the EventBox widget might
appear to be totally useless. It draws nothing on the screen and responds
to no events. However, it does serve a function - it provides an X window
for its child widget. This is important as many GTK widgets do not have
an associated X window. Not having an X window saves memory and improves
performance, but also has some drawbacks. A widget without an X window
cannot receive events, does not perform any clipping on its contents and
cannot set its background color. Although the name EventBox emphasizes
the event-handling function, the widget can also be used for clipping.
(and more, see the example below).
To create a new EventBox widget, use:
event_box = GtkEventBox()
|
A child widget can then be added to this
EventBox:
event_box.add(child_widget)
|
The eventbox.py
example program demonstrates both uses of an EventBox - a label is created
that is clipped to a small box, has a green background and is set up so
that a mouse-click on the label causes the program to exit. Resizing the
window reveals varying amounts of the label. Figure 10.1 illustrates the
programs display:

Figure 10.1 Event Box Example
The source code for
eventbox.py is:
1 #!/usr/bin/env python
2
3 # example-start eventbox eventbox.c
4
5 import gtk
6 import GDK
7
8 class EventBoxExample:
9 def __init__(self):
10 window = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL)
11 window.set_title("Event Box")
12 window.connect("destroy", gtk.mainquit)
13 window.set_border_width(10)
14
15 # Create an EventBox and add it to our toplevel window
16 event_box = gtk.GtkEventBox()
17 window.add(event_box)
18 event_box.show()
19
20 # Create a long label
21 label = gtk.GtkLabel("Click here to quit, quit, quit, quit, quit")
22 event_box.add(label)
23 label.show()
24
25 # Clip it short.
26 label.set_usize(110, 20)
27
28 # And bind an action to it
29 event_box.set_events(GDK.BUTTON_PRESS_MASK)
30 event_box.connect("button_press_event", gtk.mainquit)
31
32 # More things you need an X window for ...
33 event_box.realize()
34 event_box.get_window().set_cursor(gtk.cursor_new(GDK.HAND1))
35
36 # Set background color to green
37 style = event_box.get_style().copy()
38 style.bg[gtk.STATE_NORMAL] = event_box.get_colormap().alloc('green')
39 event_box.set_style(style)
40
41 window.show()
42
43 def main():
44 gtk.mainloop()
45 return 0
46
47 if __name__ == "__main__":
48 EventBoxExample()
49 main()
|