#!/usr/bin/env python
import qt

sigAddCachedWidget = qt.PYSIGNAL('hi, patrick!')

def widget_indexer(start=0):
    while True:
        yield start
        start += 1

class MainForm(qt.QMainWindow):
    def __init__(self):
        qt.QMainWindow.__init__(self)
        layout = qt.QVBoxLayout(self)
        layout.setAutoAdd(True)

        self.label = qt.QLabel('0', self)
        self.adder = qt.QPushButton('Add More', self)
        self.closer = qt.QPushButton('Close', self)

        self.connect(self, sigAddCachedWidget, self.addCacheWidget)
        self.connect(self.adder, qt.SIGNAL('clicked()'), self.requestFillCache)
        self.connect(self.closer, qt.SIGNAL('clicked()'), self.close)
        self.cache = {}

        self.indexer = widget_indexer().next
        timer = qt.QTimer.singleShot(3, self.requestFillCache)

    def requestFillCache(self):
        print 'emitting signals to fill a widget cache'
        for index in [self.indexer() for i in range(100)]:
            ctor = qt.QWidget # or some other constructor
            wname = 'Widget Name: %s' % (index, )
            self.emit(sigAddCachedWidget, (ctor, wname))

    def addCacheWidget(self, init, name):
        self.cache[name] = widget = init(self, name)
        self.label.setText('%s items in cache' % (len(self.cache), ))
        
if __name__ == '__main__':
    app = qt.QApplication([])
    win = MainForm()

    app.connect(app, qt.SIGNAL('lastWindowClosed()'), app, qt.SLOT('quit()'))
    app.setMainWidget(win)

    win.show()
    app.exec_loop()
