如何在 QMessageBox 小部件中居中文本和按钮

我正在制作 QMessageBox,但无法将弹出窗口中的文本和按钮居中。

这是我的消息框代码:

def update_msgbox(self):
        self.msg = QMessageBox(self.centralwidget)
        self.msg.setWindowTitle("  Software Update")
        self.msg.setText("A software update is available. \nDo you want to update now?")
        self.msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        self.msg.setStyleSheet("QLabel{min-width: 200px;}")
        self.msg.exec_()

这是弹出窗口当前的样子:

如何在 QMessageBox 小部件中居中文本和按钮

有没有办法让文本居中并使按钮居中?

iCMS 回答:如何在 QMessageBox 小部件中居中文本和按钮

一种可能的解决方案是移除(或在必要时删除)元素并将它们添加回布局:

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication,QMessageBox,QLabel,QDialogButtonBox


class MessageBox(QMessageBox):
    def __init__(self,parent=None):
        super().__init__(parent)
        grid_layout = self.layout()

        qt_msgboxex_icon_label = self.findChild(QLabel,"qt_msgboxex_icon_label")
        qt_msgboxex_icon_label.deleteLater()

        qt_msgbox_label = self.findChild(QLabel,"qt_msgbox_label")
        qt_msgbox_label.setAlignment(Qt.AlignCenter)
        grid_layout.removeWidget(qt_msgbox_label)

        qt_msgbox_buttonbox = self.findChild(QDialogButtonBox,"qt_msgbox_buttonbox")
        grid_layout.removeWidget(qt_msgbox_buttonbox)

        grid_layout.addWidget(qt_msgbox_label,alignment=Qt.AlignCenter)
        grid_layout.addWidget(qt_msgbox_buttonbox,1,alignment=Qt.AlignCenter)


def main():
    app = QApplication([])

    msg = MessageBox()

    msg.setWindowTitle("Software Update")
    msg.setText("A software update is available.<br>Do you want to update now?")
    msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
    msg.setStyleSheet("QLabel{min-width: 200px;}")

    msg.exec_()


if __name__ == "__main__":
    main()
本文链接:https://www.f2er.com/439545.html

大家都在问