Search code examples
python-2.7pyqtqwidgetqmainwindowqpushbutton

QMainwindow doesn't show when I clicked a qpushbutton into a QWidget


I have a QWidget (login form) and QMainWindow(main form). the problem is when I clicked a qpushbutton into the qwidget the QmainWindow should appear, but It doesn't.

class Ui_frmInicial(QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.resize(400, 250)
        self.btnOpen = QtGui.QPushButton(self)
        self.btnOpen.setGeometry(QtCore.QRect(110, 170, 111, 41))
        self.btnOpen.clicked.connect(self.btnOpen_clicked)
    def btnOpen_clicked(self):
        print('ok ')
        #mform = Ui_mainForm()
        #mform.show()
if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    ui = Ui_frmInicial()
    ui.show()
    sys.exit(app.exec_())

and the other class is:

class Ui_mainForm(QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        print('ok')
        self.resize(928, 695)
        QtCore.QMetaObject.connectSlotsByName(self)

what would be the mistake? I run the project from Ui_frmInicial. In the console I show the print 'ok' into the init() function but the qmainwindow doesn't show. Thanks in advance


Solution

  • You need to ensure, the window you're opening is not deleted immediately after show is called.

    I would suggest, you define the window in the main scope and init the form with it:

    class Ui_frmInicial(QWidget):
        def __init__(self, window):                         #window parameter
            QtGui.QWidget.__init__(self)
            self.resize(400, 250)
            self.btnOpen = QtGui.QPushButton(self)
            self.btnOpen.setGeometry(QtCore.QRect(110, 170, 111, 41))
            self.btnOpen.clicked.connect(lambda c: window.show()) #lambda callback
    
    if __name__ == "__main__":
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Ui_mainForm()                              #window definition
        ui = Ui_frmInicial(window)                          #ui initialisation
        ui.show()
        sys.exit(app.exec_())
    

    Or at least as a member of the form.