How to use layout managers in PyQt5 to manage window components?

In PyQt5, layout managers can be used to control the position and size of window widgets. Commonly used layout managers include QHBoxLayout, QVBoxLayout, and QGridLayout.

Here is a simple example demonstrating how to use a layout manager to manage window components.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

class MyWindow(QWidget):
    def __init__(self):


    def initUI(self):
        self.setGeometry(100, 100, 300, 200)

        button1 = QPushButton('按钮1', self)
        button2 = QPushButton('按钮2', self)
        button3 = QPushButton('按钮3', self)

        layout = QVBoxLayout()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()

In this example, we have created a QWidget window and added three QPushButton buttons to it. We then used the QVBoxLayout layout manager to arrange these three buttons vertically in the window.

By running this code, you will see three buttons aligned vertically in the window. Using a layout manager like this makes it easy to arrange window components, making it more flexible and easier to manage.

Leave a Reply 0

Your email address will not be published. Required fields are marked *