PyQt5 uses stackedWidget to implement page switching

Foreword

This article is an introductory tutorial for PyQt5, specifically the following four steps

  • 1. Use Qt Designer to design the page and convert the UI file into a .py file
  • 2. Create a new .py file to call the UI file
  • 3. Set button click event to switch pages

1. Use Qt Designer to design the page and convert the UI file into a .py file

First open the Qt Designer software and create a new MainWindow (if you don’t have Qt Designer software, you can skip this section and directly copy the ui code at the end of the py file)

At this time, you can search for the stackedWidget we need to use through the upper left corner.

Drag it into our interface and manually resize it with the mouse

At this point we can add any controls inside, or add a label control outside the control.

At this point we can switch by clicking the small arrow in the upper right corner of the stackedWidget

After entering this interface, we still add controls in the same position

At this point our design is complete. After saving it to a convenient location, we start converting it to a .py file.

At this time, enter cmd at the path and press Enter

Enter pyuic5 untitled.ui -o ui.py and press Enter

Analysis:

  • pyuic5: This is the user interface compiler for PyQt5, which accepts .ui files and converts them into Python code.
  • untitled.ui: This is the name of the .ui file you want to convert.
  • -o: This is an option that means “output”. It tells pyuic5 which file you want the output to be saved to.
  • ui.py: This is the name of the output file. In other words, this command will create a Python file named “ui.py” that contains the code converted from “untitled.ui”.

At this time, when you return to the folder, you will find that the python file has been converted.

Generated ui code:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget)
        self.stackedWidget.setGeometry(QtCore.QRect(170, 70, 421, 341))
        self.stackedWidget.setObjectName("stackedWidget")
        self.page_3 = QtWidgets.QWidget()
        self.page_3.setObjectName("page_3")
        self.label = QtWidgets.QLabel(self.page_3)
        self.label.setGeometry(QtCore.QRect(180, 60, 72, 15))
        self.label.setObjectName("label")
        self.pushButton = QtWidgets.QPushButton(self.page_3)
        self.pushButton.setGeometry(QtCore.QRect(160, 230, 93, 28))
        self.pushButton.setObjectName("pushButton")
        self.stackedWidget.addWidget(self.page_3)
        self.page_4 = QtWidgets.QWidget()
        self.page_4.setObjectName("page_4")
        self.label_3 = QtWidgets.QLabel(self.page_4)
        self.label_3.setGeometry(QtCore.QRect(180, 60, 72, 15))
        self.label_3.setObjectName("label_3")
        self.pushButton_2 = QtWidgets.QPushButton(self.page_4)
        self.pushButton_2.setGeometry(QtCore.QRect(160, 230, 93, 28))
        self.pushButton_2.setObjectName("pushButton_2")
        self.stackedWidget.addWidget(self.page_4)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(340, 460, 72, 15))
        self.label_2.setObjectName("label_2")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        self.retranslateUi(MainWindow)
        self.stackedWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "First Page"))
        self.pushButton.setText(_translate("MainWindow", "Switch to the second page"))
        self.label_3.setText(_translate("MainWindow", "Second Page"))
        self.pushButton_2.setText(_translate("MainWindow", "Switch the first page"))
        self.label_2.setText(_translate("MainWindow", "TextLabel"))

2. Create a new .py file to call the UI file

We open the folder in the programming software and create a new .py file

At this point we start writing reference code

import sys #Import sys module, used to process command line parameters and exit the program
from PyQt5.QtWidgets import QMainWindow, QApplication # Import the QMainWindow and QApplication classes from the PyQt5.QtWidgets module
from ui import Ui_MainWindow # Import the Ui_MainWindow class from the ui module, which defines the user interface of the main window

class MainWindow(QMainWindow, Ui_MainWindow): # Define a class named MainWindow, inherited from QMainWindow and Ui_MainWindow
    def __init__(self): # Constructor of class
        super().__init__() # Call the constructor of the parent class to initialize the main window
        self.setupUi(self) #Call the setupUi method to associate the user interface with the main window

if __name__ == "__main__": # If the current script is run as the main program
    app = QApplication(sys.argv) # Create a QApplication object to manage the control flow and main settings of the GUI application
    main = MainWindow() # Create a MainWindow object, which is the main window instance
    main.show() # Display the main window
    sys.exit(app.exec_()) # Enter the event loop, wait for user operations and handle events, and then exit the program

Analysis of the above code:

First, it imports the necessary modules and classes, including sys, QMainWindow, QApplication and the custom Ui_MainWindow kind. Then, it defines a class named MainWindow, which inherits from QMainWindow and Ui_MainWindow. In the constructor of the MainWindow class, it calls the constructor of the parent class to initialize the main window and associates the user interface with the main window by calling the setupUi method.

Finally, in the if __name__ == "__main__" statement block, it creates a QApplication object and a MainWindow object. By calling the show method, it displays the main window. Then it enters the event loop, waits for user actions and handles events. When the user closes the main window or performs an exit operation, the program will call the sys.exit method to exit.

When you run the program at this time, you can see the UI interface we designed.

3. Set button click event to switch pages

At this point we set up two click events, corresponding to the buttons of the two interfaces.

 def click_button1(self):
        self.stackedWidget.setCurrentIndex(1)

    def click_button2(self):
        self.stackedWidget.setCurrentIndex(0)

Analysis: Take click_button2 as an example – this method will be called when the user clicks the button. Its function is to set the current index of stackedWidget to 0. This means that when the user clicks button 2, the first page will be displayed (pages are counted from 0, page 0 is what we call the first page)

At this point we associate the button control with the event

 self.pushButton.clicked.connect(self.click_button1)
        self.pushButton_2.clicked.connect(self.click_button2)

Analysis: Take the first line as an example – this line of code connects the click event of pushButton with the click_button1 method. When the user clicks pushButton, the click_button1 method will be called

At this point we can run the interface to view our application

(before clicking)

(after clicking)

You can click it repeatedly. If no problem occurs, it means there is no problem. Since we are switching the page locally, the external label does not change with the internal changes.

Summary

The complete code is as follows

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication
from ui import Ui_MainWindow

class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.pushButton.clicked.connect(self.click_button1)
        self.pushButton_2.clicked.connect(self.click_button2)

    def click_button1(self):
        self.stackedWidget.setCurrentIndex(1)

    def click_button2(self):
        self.stackedWidget.setCurrentIndex(0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

The above is my production process. If you encounter any questions or there are errors in the article, please send a private message or comment.