Joe Malley
Joe Malley

Reputation: 11

How to create a new widget when pressing a button in PyQt5

I am very new to PyQt5 and am making a simple program where the user is first presented with a choice of two buttons, when they press one it should take them to a new screen, when they press the other it should take them to a different screen. I am having trouble getting a new widget to open when pressing the button. The way I have tried to do this is by having a function that creates the widget and this function is run when the user presses the button, but currently the widget is not being created by the function.

Here is my code.

def StudentLog():
    class StudentLogin(QWidget):
        def __init__(self):
            super().__init__()
            self.initUI()

        def initUI(self):
            self.setGeometry(300, 300, 300, 200)
            self.setWindowTitle('Student log in screen')    
            self.show()


class Login(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()        

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))       
        self.setToolTip('Login screen')
        btn = QPushButton('Student Login', self)
        btn.setToolTip('This will log you in as a student')
        btn.move(10, 50)  
        btn.clicked.connect(StudentLog)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Log in screen')    
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Login()
    sys.exit(app.exec_())

Upvotes: 1

Views: 2834

Answers (1)

PRMoureu
PRMoureu

Reputation: 13317

The issue here is that you are only declaring a class inside your function StudentLog(), and then you never create an instance of this class.

I suggest to move this function inside the class Login, to create a method you can easily call too in order to create this instance, and the advantage is you can keep a track of the new widget by using self. :

class StudentLogin(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Student log in screen')
        self.show()


class Login(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        QToolTip.setFont(QFont('SansSerif', 10))
        self.setToolTip('Login screen')
        btn = QPushButton('Student Login', self)
        btn.setToolTip('This will log you in as a student')
        btn.move(10, 50)
        btn.clicked.connect(self.student_log)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Log in screen')
        self.show()

    def student_log(self):
        self.widget = StudentLogin()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Login()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions