Skip to content

[PyQt5] Open another window in the main window

Last Updated on 2021-06-26 by Clay

As mentioned in the title, when we use PyQt5 compose the interface, we often need another sub-window that is different from the main window. It may be a different function, it may be a setting of the main program … anything is possible.

In PyQt5, it is not so difficult to open another window. Below, I use a simple example to demo how to open the sub-window.


Open Window

To complete another window is actually very simple: just write another window program. For example, I now have a main window:

class MainWindow(QMainWindow):
     def __init__(self):
         super(MainWindow, self).__init__()
         self.resize(400, 300)

         # Button
         self.button = QPushButton(self)
         self.button.setGeometry(0, 0, 400, 300)
         self.button.setText('Main Window')
         self.button.setStyleSheet('font-size:40px')

         # Sub Window
         self.sub_window = SubWindow()

         # Button Event
         self.button.clicked.connect(self.sub_window.show)



At the same time, I also have another sub-window that is about to be opened:

class SubWindow(QWidget):
     def __init__(self):
         super(SubWindow, self).__init__()
         self.resize(400, 300)

         # Label
         self.label = QLabel(self)
         self.label.setGeometry(0, 0, 400, 300)
         self.label.setText('Sub Window')
         self.label.setAlignment(Qt.AlignCenter)
         self.label.setStyleSheet('font-size:40px')



Then when I click the button of the main window, it will show the window of the sub-window:

There is a button on the main window
Click to open a sub-window

Basically it’s just that. Is it quite simple?


Complete Code

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class MainWindow(QMainWindow):
     def __init__(self):
         super(MainWindow, self).__init__()
         self.resize(400, 300)

         # Button
         self.button = QPushButton(self)
         self.button.setGeometry(0, 0, 400, 300)
         self.button.setText('Main Window')
         self.button.setStyleSheet('font-size:40px')

         # Sub Window
         self.sub_window = SubWindow()

         # Button Event
         self.button.clicked.connect(self.sub_window.show)


class SubWindow(QWidget):
     def __init__(self):
         super(SubWindow, self).__init__()
         self.resize(400, 300)

         # Label
         self.label = QLabel(self)
         self.label.setGeometry(0, 0, 400, 300)
         self.label.setText('Sub Window')
         self.label.setAlignment(Qt.AlignCenter)
         self.label.setStyleSheet('font-size:40px')


if __name__ == '__main__':
     app = QApplication([])
     window = MainWindow()
     window.show()
     sys.exit(app.exec_())




References

3 thoughts on “[PyQt5] Open another window in the main window”

Leave a Reply