1

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_())

2 Answers2

0

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_())
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
0

The dialog closes immediately because you are not keeping a reference to it, and so it will get garbage-collected as soon as it goes out of scope.

The simplest way to fix it would be to do something like this:

    def handleButton(self):
        self.dialog = AddBooking2()
        self.dialog.show()

and you can also remove the self.show() lines from AddBooking2.__init__ and HomeScreen.__init__, which are redundant. Other than that, your code looks fine.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336