Skip to content Skip to sidebar Skip to footer

Load Other Windows When Button Clicked. Pyqt

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, c

Solution 1:

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

classHomeScreen(QtGui.QWidget):
    def__init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_HomeScreen()
        self.ui.setupUi(self)

    @pyqtSlot("")defon_Add_Booking_Button_clicked(self): # The connection is carried by the Ui_* classes generated by pyuic4
        addbooking = AddBooking2()
        addbooking.show()


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

Solution 2:

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:

defhandleButton(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.

Post a Comment for "Load Other Windows When Button Clicked. Pyqt"