PyQt5 series of tutorials (thirty-eight) multi-window

Software and hardware environment

  • Windows 10 64bit
  • Anaconda3 with python 3.8
  • PyQt5 5.15


In actual projects, multi-window is a very common operation. This article will take a look at the implementation of multi-window in PyQt5 .


We make two windows, there is a button in the main window, and the second window pops up after clicking the button

The interface is designed through the designer , which are as follows

Put a label in the second window, add some text

After the interface is completed, the ui file is obtained, and the ui is converted into a py file through pyuic5.bat . The command is as follows

 pyuic5.bat -o mainwindow.ui pyuic5.bat -o .secondwindow.ui

Next, write the file code corresponding to the two windows, the main window is

 import sys from PyQt5.QtWidgets import QMainWindow, QApplication from ui_mainwindow import Ui_MainWindow from second_window import SecondWindow class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) # 按钮点击处理self.pushButton.clicked.connect(self.showSecondWindow) def showSecondWindow(self): # 实例化第二个窗口,然后进行show,这里保留主窗口的显示。 self.secWin = SecondWindow() # 窗口的关闭调用self.secWin.close()方法 if __name__ == '__main__': # 常规的app启动步骤app = QApplication(sys.argv) windows = MainWindow() sys.exit(app.exec_())

The second window is very simple, just display it

 from PyQt5.QtWidgets import QMainWindow from ui_secondwindow import Ui_MainWindow class SecondWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(SecondWindow, self).__init__(parent) self.setupUi(self)

Run , you can see

Usually, when opening a new window, some values ​​will be passed in the past, for this case, let’s also look at an example

Modify the constructor of , add a parameter to receive a string, and then display the string on the label control

 def __init__(self, param, parent=None): super(SecondWindow, self).__init__(parent) self.setupUi(self) print("从主窗口传递过来的字符是:{}".format(param)) self.label.setText(param)

Go back to the place called in , bring the string parameters to be passed when instantiating, and other data types are similar

 def showSecondWindow(self): self.secWin = SecondWindow("Hello SecondWindow.")

The final execution result is like this

Source code download

PyQt5 series of tutorials

For more PyQt5 tutorials, please move to

This article is transferred from
This site is only for collection, and the copyright belongs to the original author.