Welcome, guest | Sign In | My Account | Store | Cart

A function which enables you to connect to and emit signals from (almost) any python object without having to subclass qt.QObject in PyQT.

Python, 30 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import qt
import weakref

_emitterCache = weakref.WeakKeyDictionary()

def emitter(ob):
    """Returns a QObject surrogate for *ob*, to use in Qt signaling.

    This function enables you to connect to and emit signals from (almost)
    any python object with having to subclass QObject.

      >>> class A(object):
      ...   def notify(self, *args):
      ...       QObject.emit(emitter(self), PYSIGNAL('test'), args)
      ...
      >>> ob = A()
      >>> def myhandler(*args): print 'got', args
      ...
      >>> QObject.connect(emitter(ob), PYSIGNAL('test'), myhandler)
      ... True
      >>> ob.notify('hello')
      got ('hello',)

      >>> QObject.emit(emitter(ob), PYSIGNAL('test'), (42, 'abc',))
      got (42, 'abc')
    """

    if ob not in _emitterCache:
        _emitterCache[ob] = qt.QObject()
    return _emitterCache[ob]

In PyQt applications it is often desirable to connect objects from the model domain to Qt widgets. Qt requires objects which emit signals to inherit QObject. This may sometimes be too restrictive or cumbersome. For example, objects which inherit QObject are not pickleable. Also classes can't derive from both object and QObject. This function provides a non invasive way to allow model objects to participate in Qt signalling.

This simple solution associates a QObject instance for each object passed to the emitter function. When the object is no longer referenced the assocation is removed, thereby freeing the QObject which will subsequently be removed from the Qt signalling system.

Created by Tom Dossis on Sun, 2 Jan 2005 (PSF)
Python recipes (4591)
Tom Dossis's recipes (1)

Required Modules

Other Information and Tasks