Search code examples
pythonpyqt4

PyQt4: How do I switch from one window to another on a click of a button


So im building an "TeacherPortal" for my python class and the teacher wants us to go to another window from a click of a button specifically using PyQt4. I have looking around but I only found out for PyQt5 and im still very new to GUI's

I have tried creating 2 different classes one for the main window and the other for the second window(they are separate classes) and I put a button with it linked to the other class but it doesn't work

from PyQt4 import QtGui, QtCore
import sys

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window,self).__init__()
        self.setWindowTitle("TeahcherPortal")
        self.setGeometry(50,50,800,600)

        self.FirstWindow()

    def FirstWindow(self):
        btn = QtGui.QPushButton("Login",self)
        btn.clicked.connect(SecondPage())
        btn.move(400,300)

        self.show()

class SecondPage(QtGui.QMainWindow):
    def __init__(self):
        super(SecondPage,self).__init__()
        self.setGeometry(50,50,800,600)



def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    Page = SecondPage()
    sys.exit(app.exec_())

run()

I expected it to go to the other window but that doesn't happen sadly. But what does happen is I get a error TypeError: connect() slot argument should be a callable or a signal, not 'SecondPage'


Solution

  • Try it:

    import sys
    # PyQt5
    from PyQt5.QtCore    import *
    from PyQt5.QtWidgets import *
    from PyQt5.QtGui     import *
    
    # PyQt4
    #from PyQt4.QtCore    import *
    #from PyQt4.QtGui     import *
    
    class Window(QMainWindow):
        def __init__(self):
            super(Window,self).__init__()
            self.setWindowTitle("TeahcherPortal")
            self.setGeometry(50,50,800,600)
    
            self.FirstWindow()
    
        def FirstWindow(self):
            btn = QPushButton("Login", self)
            btn.clicked.connect(self.secondPage)    # - (SecondPage())
            btn.move(400,300)
    
            self.show()
    
        def secondPage(self):                       # +++
            self.secondWindow = SecondPage()
            self.secondWindow.show()
    
    class SecondPage(QMainWindow):     
        def __init__(self):
            super(SecondPage,self).__init__()
            self.setWindowTitle("SecondPage")
            self.setGeometry(50,50,800,600)
    
    
    def run():
        app = QApplication(sys.argv)
        GUI = Window()
        Page = SecondPage()
        sys.exit(app.exec_())
    
    run()
    

    enter image description here