#!/bin/env python

import qt
import qtui
import sip

import tester

## apa = sip.unwrapinstance(labelWidget)
## foo = sip.wrapinstance(apa, qt.QLabel)
## labelWidget = foo

testForm = 'test.ui'

class Test(tester.Tester):
    def __init__(self, parent):
        tester.Tester.__init__(self, parent)

        self._form = None
        
        self.placeholder = qt.QVBoxLayout(self._frame)

        self._timer = qt.QTimer()
        self.connect(self._timer, qt.SIGNAL('timeout()'),
                     self.updateView)
        
    def updateView(self):
        if self._form:
            oldForm = self._form
            self._form = None
            self.placeholder.remove(oldForm)
            oldForm.close()
            oldForm.deleteLater()
            
        newForm = qtui.QWidgetFactory.create(testForm, None,
                                             self._frame)
        self.placeholder.addWidget(newForm)
        self._form = newForm
        self._form.show()
        self._updateLabels()

    def autoUpdateChanged(self, auto):
        """
        """
        self.button.setEnabled(not auto)
        if auto:
            if not self._timer.isActive():
                self._timer.start(100)
            return

        self._timer.stop()
    def _updateLabels(self):
        """
        Find all widgets in the form that are named "label_*" and
        set their text to their name. 
        """
        labels = self._findLabels(self._form)
        for label in labels:
            if not isinstance(label, qt.QLabel):
                print 'label %s (%r) isn\'t a QLabel' % (label.name(), label)
            label.setText(label.name())

    def _findLabels(self, widget):
        widgetName = unicode(widget.name())

        if widgetName.startswith(u'label'):
            return [widget]

        widgets = []
        for child in widget.children():
            widgets.extend(self._findLabels(child))

        return widgets


if __name__ == '__main__':
    app = qt.QApplication([])

    w = Test(None)
    app.setMainWidget(w)
    w.show()
    app.exec_loop()
    
    
