PyQt如何将QGroupBox放置到QHBoxLayout布局的顶部
PyQt 置顶QGroupBox布局调整方案
问题根因
当前窗口直接使用QHBoxLayout作为根布局,所有添加到该布局的控件默认会水平并排排列,无法实现「单控件置顶、剩余两个控件水平排布在下方」的分层效果,需要通过嵌套布局实现分层结构。
调整步骤
- 将窗口根布局从
QHBoxLayout替换为QVBoxLayout,实现垂直方向的上下分层:第一行放置标题为“Datum und Uhrzeit”的日期时间组框,第二行放置下方的水平内容区。 - 新建一个
QHBoxLayout作为下方内容区的布局容器,将“Aktionen”操作组框、“Kundenliste”客户列表组框添加到这个水平布局中。 - 给客户列表组框设置拉伸因子,让它自动占满水平布局的剩余宽度,匹配目标效果的宽度占比。
修正后可运行代码
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QGroupBox, QGridLayout, QLabel from PyQt5.QtCore import Qt # 请提前导入项目内的ActionButton模块 def __init__(self, *args, **kwargs): super().__init__() self.setWindowTitle('Wydbid - Center') self.setGeometry(0, 0, 1920, 1080) # 根布局替换为垂直布局,实现上下分层 self.setLayout(QVBoxLayout()) self.layout().setContentsMargins(30, 30, 30, 30) self.setupUI() def setupUI(self): datetime = QGroupBox(parent=self, title='Datum und Uhrzeit') datetime.setFixedHeight(150) action_list = QGroupBox(parent=self, title='Aktionen') action_list.setFixedWidth(200) action_list.setLayout(QGridLayout()) action_list.layout().setAlignment(Qt.AlignTop| Qt.AlignHCenter) customer_note = QLabel(parent=action_list, text='Kunden') add_customer = ActionButton.ActionButton(parent=action_list, text='Kunde hinzufügen ➜') action_list.layout().addWidget(customer_note, 0, 0, 1, 0, Qt.AlignLeft) action_list.layout().addWidget(add_customer, 1, 0, 1, 0, Qt.AlignCenter) customer_list_box = QGroupBox(parent=self, title='Kundenliste') # 新建下方区域的水平布局 bottom_layout = QHBoxLayout() bottom_layout.addWidget(action_list) # 设置拉伸因子为1,让客户列表自动占满剩余宽度 bottom_layout.addWidget(customer_list_box, stretch=1) # 按顺序往根垂直布局添加内容:先加顶部日期组,再加下方水平布局 self.layout().addWidget(datetime) self.layout().addLayout(bottom_layout)
效果对比
- 调整前错误运行效果:

- 调整后目标实现效果:

内容的提问来源于stack exchange,提问作者Niklas Wild
相关产品推荐
相关产品推荐

