from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMessageBox, QLabel, QDialogButtonBox
from PyQt5.QtGui import QIcon, QPixmap
import sys
class MessageBox(QMessageBox):
def __init__(self, parent=None):
super().__init__(parent)
"""子控件居中"""
grid_layout = self.layout()
msg_icon_lab = self.findChild(QLabel, "qt_msgboxex_icon_label")
msg_icon_lab.deleteLater()
msg_lab = self.findChild(QLabel, "qt_msgbox_label")
msg_lab.setAlignment(Qt.AlignCenter)
grid_layout.removeWidget(msg_lab)
msg_btn_box = self.findChild(QDialogButtonBox, "qt_msgbox_buttonbox")
grid_layout.removeWidget(msg_btn_box)
grid_layout.addWidget(msg_lab, 0, 0, alignment=Qt.AlignCenter)
grid_layout.addWidget(msg_btn_box, 1, 0, alignment=Qt.AlignCenter)
self.init_setup()
def init_setup(self):
"""设置消息窗口图标、按钮和按钮文本、标签最小宽度、和标签提示内容"""
icon = QIcon()
icon.addPixmap(QPixmap('R-C.png'))
self.setWindowIcon(icon)
self.setWindowTitle("提示:")
self.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
self.button(QMessageBox.Ok).setText("确定")
self.button(QMessageBox.Cancel).setText("取消")
self.setStyleSheet("QLabel{min-width: 300px;}")
self.setText("这个是提示窗口,点击确定按钮继续执行,<br>点击取消按钮将结束执行。")
self.exec_()
if __name__ == "__main__":
app = QApplication(sys.argv)
msg = MessageBox()
sys.exit(app.exec_())
以下为设置后的显示效果: