You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyQt5中为QLabel和QPushButton添加QVBoxLayout布局?

How to Add QVBoxLayout to QLabel and QPushButton in QMainWindow

Hey there! To use QVBoxLayout with your QLabel and QPushButton in a QMainWindow, you need to remember that QMainWindow relies on a central widget to hold custom layouts (you can’t set the layout directly on the main window itself). Here’s how to modify your code to get the vertical layout working:

Modified Code

from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QToolTip, QLabel, QWidget, QVBoxLayout
import sys

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.title = "pyQt5"
        self.top = 100
        self.left = 100
        self.width = 680
        self.height = 500

        # Set basic window properties
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create a central widget to act as the container for our layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # Initialize QVBoxLayout and attach it to the central widget
        vertical_layout = QVBoxLayout(central_widget)

        # Create your label and button (no need to pass self as parent—layout handles this)
        lb = QLabel('Hi')
        button = QPushButton("print")

        # Add widgets to the vertical layout (they'll stack top to bottom)
        vertical_layout.addWidget(lb)
        vertical_layout.addWidget(button)

        # Optional: Add flexible space at the bottom to push widgets upward
        vertical_layout.addStretch()

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

Key Changes Explained

  • Central Widget: QMainWindow has its own built-in structure (menu bar, status bar, etc.), so we need a separate QWidget to hold our custom layout. We set this as the main window’s central widget with self.setCentralWidget().
  • Layout Management: Instead of using move() for absolute positioning, we use QVBoxLayout to automatically arrange widgets vertically. The layout takes care of resizing and repositioning widgets when the window is resized.
  • Widget Parenting: We removed self as the parent from QLabel and QPushButton. The layout will assign the central widget as their parent, which keeps the widget hierarchy clean.
  • Stretch Option: The addStretch() line adds empty flexible space at the bottom of the layout, pushing your label and button to the top of the window. You can adjust this or add multiple stretches to control widget placement.

Content of the question originates from stack exchange, question author Adel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:28:00