QDialog callback launches QMainWindow

To demonstrate how a MainWindow can be opened/closed from the call-back function of a Dialog. The use case is the SardanaMonitor IVP for CursorApp.

#!/usr/bin/env python
#
#
import sys
from PyQt4 import QtCore, QtGui
import time

i = 0

class mainWindow( QtGui.QMainWindow):
    def __init__( self, parent):
        QtGui.QMainWindow.__init__(self, parent)
        self.b = QtGui.QPushButton("Hello",self)
        self.b.clicked.connect( self.launch)
        self.show()
    def launch( self):
        print( "calling quit")
        app.quit()

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        b = QtGui.QPushButton("ok",self)
        self.resize( 100, 100)
        b.clicked.connect( self.launch)
        self.mw = None

    def launch( self):
        self.timer = QtCore.QTimer( self)
        self.timer.timeout.connect( self.cb_timer)
        self.timer.start(0)

    def cb_timer( self): 
        global i
        print( "timer function", i)
        self.timer.start(1000)
        if i == 5:
           self.timer.stop()
           return
        if self.mw is None:
            self.mw = mainWindow( self)
            self.mw.b.setText( "Counter %d" % i)
            i = i + 1
        else:
            self.mw.close()
            self.mw = None

if __name__ == '__main__':
   app = QtGui.QApplication(sys.argv)
   d = Dialog()
   d.exec_()