Search code examples
pythonpyqt5pysideqt-designerqstackedwidget

Class for Each QStackedWidget Page


I am using PyQt5 and Qt-Designer to design an application.

How do I instantiate a class for each page on QstackedWidget. I can do it in a single class, all widgets belong to the same QMainWindow. But, the issue is that the file will get too long and impracticale. How do I assign a class for each page. For example, class I handles all the widgets on Page I and class II handles all the widgets on Page II; in the QMainWindow file I can just assign an Object that represents each page.

How can I do it?


Solution

  • Just create multiple modules:

    widget1.py

    from PyQt5.QtWidgets import QWidget
    class Widget1(QWidget):
        def __init__(self, *args, **kwargs):
            QWidget.__init__(self, *args, **kwargs)
    

    widget2.py

    from PyQt5.QtWidgets import QWidget
    class Widget2(QWidget):
        def __init__(self, *args, **kwargs):
            QWidget.__init__(self, *args, **kwargs)
    

    main.py

    from widget1 import Widget1
    from widget2 import Widget2
    from PyQt5.QtWidgets import QMainWindow, QApplication
    
    class MainWindow(QMainWindow):
        def __init__(self):
            QMainWindow.__init__(self)
            self.setTitle("Stackked widget demo")
            self.stacked = QStackedWidget(self)
            self.setCentralWidget(self.stacked)
            self.widget1 = Widget1()
            self.stacked.addWidget(self.widget1)
            self.widget2 = Widget2()
            self.stacked.addWidget(self.widget2)
    
    if __name__ == "__main__":
        app = QApplication([])
        mainwin = MainWindow()
        mainwin.show()
        app.exec_()