如何在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
相关产品推荐
相关产品推荐

