【问题标题】:How to center text and buttons in QMessageBox widget如何在 QMessageBox 小部件中居中文本和按钮
【发布时间】:2021-08-01 05:24:21
【问题描述】:

我正在制作一个 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_()

这是弹出窗口当前的外观:

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

【问题讨论】:

    标签: python pyqt pyqt5 qmessagebox


    【解决方案1】:

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

    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, 0, 0, alignment=Qt.AlignCenter)
            grid_layout.addWidget(qt_msgbox_buttonbox, 1, 0, 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()
    

    【讨论】:

    • 这似乎行得通。我假设如果你给出了这个答案,那么就没有标准的方法吗?
    • @yem 没错,不幸的是没有常规的方法来做到这一点
    猜你喜欢
    • 2021-07-21
    • 2021-09-15
    • 1970-01-01
    • 2021-08-03
    • 2018-09-13
    • 2012-07-28
    • 2017-02-11
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多