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

Software and hardware environment

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

Introduction

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

example

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 ui_mainwindow.py mainwindow.ui pyuic5.bat -o ui_secondwindow.py .secondwindow.ui

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

 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()方法self.secWin.show() if __name__ == '__main__': # 常规的app启动步骤app = QApplication(sys.argv) windows = MainWindow() windows.show() sys.exit(app.exec_())

The second window second_window.py 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 main_window.py , 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 second_window.py , 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 main_window.py , bring the string parameters to be passed when instantiating, and other data types are similar

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

The final execution result is like this

Source code download

https://github.com/xugaoxiang/learningPyQt5

PyQt5 series of tutorials

For more PyQt5 tutorials, please move to

https://xugaoxiang.com/category/python/pyqt5/

This article is transferred from https://xugaoxiang.com/2023/02/02/pyqt5-38-multiwindow/
This site is only for collection, and the copyright belongs to the original author.