Load other windows when button clicked. PyQt
Question: I am trying to call another window from a button click in python 2.7 using
PyQt4. The code below opens the AddBooking dialog but immediately closes it.
Im new to Gui programming, can somebody please tell me what is wrong with my
code?

    
    
    from PyQt4 import QtGui
    from HomeScreen import Ui_HomeScreen
    from AddBooking import Ui_AddBooking
    import sys
    
    class HomeScreen(QtGui.QWidget, Ui_HomeScreen):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.setupUi(self)
            self.show()
            self.Add_Booking_Button.clicked.connect(self.handleButton)
    
        def handleButton(self):
            AddBooking2()
    
    
    class AddBooking2(QtGui.QWidget, Ui_AddBooking):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.setupUi(self)
            self.show()
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        window = HomeScreen()
        window.show()
        sys.exit(app.exec_())
    


Answer: Don't use multi-inheritance and neither call `show` function inside class
initializer. The problem is that the object you are creating with
`AddBooking2()` is a temporal and it's destroyed automatically when the
function ends. So you need use some variable to reference that object
something like:

    
    
    addbooking = AddBooking2()
    addbooking.show()
    

Also, since you are working with `QtDesigner` and `pyuic4` tools you can make
connections a little bit easier. Said that, your code can be modified:

    
    
    from PyQt4 import QtGui
    from PyQt4.QtCore import pyqtSlot
    from HomeScreen import Ui_HomeScreen
    from AddBooking import Ui_AddBooking
    import sys
    
    class HomeScreen(QtGui.QWidget):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.ui = Ui_HomeScreen()
            self.ui.setupUi(self)
    
        @pyqtSlot("")
        def on_Add_Booking_Button_clicked(self): # The connection is carried by the Ui_* classes generated by pyuic4
            addbooking = AddBooking2()
            addbooking.show()
    
    
    class AddBooking2(QtGui.QWidget):
        def __init__(self, parent=None):
            QtGui.QWidget.__init__(self, parent)
            self.ui = Ui_AddBooking()
            self.ui.setupUi(self)
    
    
    if __name__ == '__main__':
        app = QtGui.QApplication(sys.argv)
        window = HomeScreen()
        window.show()
        sys.exit(app.exec_())
    

