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

如何在QDialog中将QDialogButtonBox的OK按钮居中显示

QDialog中OK按钮居中显示实现方案

你只需要调用QDialogButtonBox自带的setCenterButtons()接口即可实现按钮居中,无需额外修改布局结构。

修改步骤

  • 在创建self.buttonBox的代码之后,添加一行设置按钮居中的代码:
self.buttonBox.setCenterButtons(True)

修改后的完整代码

from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLabel
from PyQt5.QtCore import Qt

class CustomDialog(QDialog):
    def __init__(self, text, parent):
        super().__init__(parent)

        self.setFixedSize(200, 100)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.WindowTitleHint | Qt.Window
                                         | Qt.CustomizeWindowHint)
        QBtn = QDialogButtonBox.Ok

        self.buttonBox = QDialogButtonBox(QBtn)
        # 新增设置按钮居中的代码
        self.buttonBox.setCenterButtons(True)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.layout = QVBoxLayout()
        message = QLabel(text)
        self.layout.addWidget(message)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)

补充说明

这个设置对多按钮场景同样生效,如果你后续添加Cancel、Apply等其他按钮,所有按钮会整体居中显示,不需要额外调整布局规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:33:03