PyQt5: How to open a new Dialog with button click

Renegade picture Renegade · Apr 21, 2018 · Viewed 7.8k times · Source
import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.uic import loadUi

class LoginPage(QDialog):
    def __init__(self):
        super(LoginPage, self).__init__()
        loadUi('LoginPage.ui', self)

class RegisterPage(QDialog):
    def __init__(self):
        super(RegisterPage, self).__init__()
        loadUi('RegisterPage.ui', self)


class HomePage(QDialog):
    def __init__(self):
        super(HomePage, self).__init__()
        loadUi('HomePage.ui', self)
        #self.btnLoginPage.clicked.connect(self.executeLoginPage)
        #self.btnRegisterPage.clicked.connect(self.executeRegisterPage)

app = QApplication(sys.argv)
widget = HomePage()
widget.show()
sys.exit(app.exec_())

I have made 3 .ui files using qt designer.

  1. HomePage.ui
  2. LoginPage.ui
  3. RegisterPage.ui

With this code, I can display the HomePage, which has 2 buttons. When I press a button, LoginPage or RegisterPage should open.

This is where the problem comes, I do not know how do I display the other 2 Dialogs. Any help will be appreciated

Answer

eyllanesc picture eyllanesc · Apr 21, 2018

It's simple, in the slots you have to create the objects and show them:

...
class HomePage(QDialog):
    def __init__(self):
        super(HomePage, self).__init__()
        loadUi('HomePage.ui', self)
        self.btnLoginPage.clicked.connect(self.executeLoginPage)
        self.btnRegisterPage.clicked.connect(self.executeRegisterPage)

    def executeLoginPage(self):
        login_page = LoginPage()
        login_page.exec_()

    def executeRegisterPage(self):
        register_page = RegisterPage()
        register_page.exec_()
...