Event Handling

  1. PyUI Events

Using PyUI Events

PyUI has an event system that uses event objects of the class guiEvent defined in pyui.desktop. Each guiEvent has an event type that is defined in pyui.locals. The built-in event types are:

There is also "USEREVENT" which marks the position that user defined events to begin. To create a user-defined event use the getUserEvent() method to return an un-used event number.

Listen for an event, can be done at the level of Widgets or globally. To listen for an event on a particular Widget use the registerEvent() method. This accepts an event type and a handler method. When the Widgets gets an event of the specified type, it will call the handler method with the event instance as the argument.

To listen for an event globally, the registerHandler() method on the desktop can be used. This works just like registerEvent for Widgets except it is call anytime events of the specified type are generated - not only when a Widgets recieved the event.

Events in PyUI are propogated from the desktop to Windows and Frames and then down the heirarchy of Panels and Widgets within them. If an event handler method returns 0 or None, the event that it recieved will continue to be propogated, but if the handler method returns a non-zero value, the event is considered "handled" and will not propagate any further.

Widgets have a hit() method to test whether an event occurred within their boundaries. This is useful to test for scope on mouse events. guiEvent Objects also have an "id" attribute that is the id of the Widget that generated the event. This is required sometimes to ensure that Widgets only process events from themselves or Widgets that they contain.

Below is an example of adding an event handler to a Frame to track mouse movement:

import pyui

class TestFrame(pyui.widgets.Frame):

    def __init__(self):
        pyui.widgets.Frame.__init__(self, 20, 20, 150, 150, "tracker")
        self.registerEvent(pyui.locals.MOUSEMOVE, self.onMouseMove)

    def onMouseMove(self, event):
        if self.hit(event.pos):
            print "mouse moved to (%d,%d)" % (event.pos[0], event.pos[1])
        return 0
newFrame = TestFrame()

(C) Sean Riley 2002