from PyQt4 import QtCore
import kaa

class QtMainThreadCallbackEvent(QtCore.QEvent):
    __slots__ = ("_callback")
    
    TYPE = QtCore.QEvent.Type(QtCore.QEvent.User + 9476) # arbitrary unique ID

    def __init__(self, callback):
        QtCore.QEvent.__init__(self, self.TYPE)
        self._callback = callback

    def performCallback(self):
        self._callback()

    def type(self):
        return self.TYPE

class QtMainThreadCallbackListener(QtCore.QObject):
    def eventFilter(self, app, event):
        if event.type() == QtMainThreadCallbackEvent.TYPE:
            event.performCallback()
            return True
        return QtCore.QObject.eventFilter(self, app, event)

_qapp = None # main QCoreApplication whose mainloop we've hooked into

def call_from_qt_mainloop(callback):
    event = QtMainThreadCallbackEvent(callback)
    _qapp.postEvent(_qapp, event)

def initialize_kaa_thread_in_qapp(app):
    global _listener, _qapp
    _listener = QtMainThreadCallbackListener()
    _qapp = app
    _qapp.installEventFilter(_listener)
    QtCore.QObject.connect(_qapp, QtCore.SIGNAL("aboutToQuit()"),
                           kaa.main.stop)

    kaa.main.select_notifier('thread', handler = call_from_qt_mainloop,
                             shutdown = _qapp.quit)

# --------------------------------------------------------------------

import sys
from PyQt4 import QtGui
import kaa

class SearchBox(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        centralwidget = QtGui.QWidget(self)
        hboxlayout = QtGui.QHBoxLayout(centralwidget)
        self.searchEdit = QtGui.QLineEdit(centralwidget)
        hboxlayout.addWidget(self.searchEdit)
        searchButton = QtGui.QPushButton("&Search", centralwidget)
        hboxlayout.addWidget(searchButton)
        self.setCentralWidget(centralwidget)

a = QtGui.QApplication(sys.argv)

initialize_kaa_thread_in_qapp(QtGui.qApp)

def fire():
    print "kaa.Timer fired"

kaa.Timer(fire).start(1)

s = SearchBox()
s.show()
a.exec_()

kaa.main.stop()
