如何在PyQt5中为QLabel和QPushButton添加QVBoxLayout布局?
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
QWidgetto hold our custom layout. We set this as the main window’s central widget withself.setCentralWidget(). - Layout Management: Instead of using
move()for absolute positioning, we useQVBoxLayoutto automatically arrange widgets vertically. The layout takes care of resizing and repositioning widgets when the window is resized. - Widget Parenting: We removed
selfas 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
相关产品推荐
相关产品推荐

