Extending Events

Robin Dunn robin at alldunn.com
Fri Aug 4 08:10:21 PDT 2006


Lee McColl-Sylvester wrote:
> Hi Hans,
> 
>  
> 
> Thanks for that.  I have the wxWidgets book, but it in no way hints to 
> the fact you can include user data in the connect function.  Had I known 
> that, I would have solved this ages ago.  Guess I should learn to look 
> in the manual from time to time.  ;-)

Just for completeness sake, here is how it is done in wxPython.  The 
wxEvtHandler::Connect method is wrapped with code like this, where func 
is a reference to the Python object to be used for the event handler 
function:

         void Connect( int id, int lastId, int eventType, PyObject* func)
         {
             if (PyCallable_Check(func)) {
                 self->Connect(id, lastId, eventType,
                           (wxObjectEventFunction) 
&wxPyCallback::EventThunker,
                           new wxPyCallback(func));
             }
             else if (func == Py_None) {
                 self->Disconnect(id, lastId, eventType,
                                  (wxObjectEventFunction)
                                  &wxPyCallback::EventThunker);
             }
             else {
                 wxPyBLOCK_THREADS(
                     PyErr_SetString(PyExc_TypeError, "Expected callable 
object or None."));
             }
         }


wxPyCallback::EventThunker is fairly large so I won't show all of it 
here.  You can find it in wxPython/src/helpers.cpp if you need more info 
about it.  In essence it gets the wxPyCallback instance from the event:

void wxPyCallback::EventThunker(wxEvent& event) {
     wxPyCallback*   cb = (wxPyCallback*)event.m_callbackUserData;
     PyObject*       func = cb->m_func;

It then wraps a Python proxy object around the event object, and calls 
func passing it that proxy.


-- 
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!





More information about the wx-users mailing list