I'm making a QMessageBox and was having trouble centering the text and the buttons in the pop up window.
This is the code that I have for the message box:
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_()
and this is the way the popup window currently looks:
Is there a way to center the text and to center the buttons?
A possible solution is to remove (or delete if necessary) the elements and add them back to the layout:
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()