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

如何在PyQt/PySide中为主窗口实现圆角边框?

在PyQt/PySide中为主窗口设置圆角边框的最简方法

你直接给QMainWindow加border-radius样式无效,核心问题有两个:一是QMainWindow的结构包含子组件(比如中央部件),样式不会直接作用到窗口外层;二是系统默认的窗口框架(标题栏、边框)会覆盖自定义样式。下面是最简可行的实现方案:

关键步骤

  • 关闭系统窗口框架,让窗口变成无框状态,才能完全自定义外观
  • 设置窗口背景透明,确保圆角外的区域不会显示默认背景
  • 给窗口设置背景色和圆角样式
  • 可选:实现窗口拖动功能(因为去掉了系统标题栏,默认无法拖动)

完整示例代码(PySide6)

from PySide6.QtWidgets import QApplication, QMainWindow
from PySide6.QtCore import Qt, QPoint
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # 1. 去掉系统窗口框架
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 2. 设置窗口背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)
        # 3. 设置圆角和背景样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #ffffff;
                border-radius: 10px;
            }
        """)
        # 设置窗口大小,方便查看效果
        self.resize(400, 300)
        self.show()

    # 实现窗口拖动功能(可选)
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_pos = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.move(event.globalPosition().toPoint() - self.drag_pos)
            event.accept()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

代码说明

  • Qt.FramelessWindowHint:移除系统自带的标题栏和边框,让我们能完全控制窗口外观
  • Qt.WA_TranslucentBackground:让窗口背景透明,这样圆角以外的区域会显示桌面背景,而不是默认的灰色
  • 样式表中必须指定background-color,否则窗口会完全透明,看不到内容
  • 拖动功能是可选的,如果不需要拖动窗口,可以去掉mousePressEvent和mouseMoveEvent的重写

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 23:10:55