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

如何让PyQt5中的布局填满除标题栏外的整个窗口

消除PyQt5布局与窗口边缘的间隙

你的问题出在QVBoxLayout默认自带内容边距,这会让布局和窗口边缘之间产生空隙。要消除这些间隙,只需要给布局设置内容边距为0即可。

修改后的代码如下:

import sys
from PyQt5 import QtWidgets, QtCore

def main():
    app = QtWidgets.QApplication(sys.argv)
    win = QtWidgets.QWidget()

    win.setFixedSize(225,150)

    label = QtWidgets.QLabel("Some Label")
    label.setAlignment(QtCore.Qt.AlignCenter)
    label.setStyleSheet('background: red')

    layout = QtWidgets.QVBoxLayout()
    # 设置布局的内容边距为0,消除与窗口边缘的间隙
    layout.setContentsMargins(0, 0, 0, 0)
    # 如果后续添加多个控件,需要控件之间无间隙,可添加下面一行
    # layout.setSpacing(0)
    layout.addWidget(label)

    win.setLayout(layout)

    win.show()
    sys.exit(app.exec_())

main()

setContentsMargins(left, top, right, bottom)方法的四个参数分别对应布局左、上、右、下四个方向的边距,全部设为0就能让布局完全填满窗口的客户区(除标题栏外的区域)。如果后续在布局中添加多个控件,还可以通过setSpacing(0)消除控件之间的默认间距。

内容的提问来源于stack exchange,提问作者Itsjul1an

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:05:09