QMessageBox

../_images/5_5_qmessagebox_sample.png

The QMessageBox class provides users information or a window for Q&A.

The message box is often used to check for an action. ( QMessageBox official document )

The message box displays the default text that describes the situation to the user. Then it can deliver information or display text that asks for the user’s opinions.

Finally it can display further details about the situation.

You can use setText()/setInformativeText()/setDetailedText() methods to display the mentioned texts.


Example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox


class MyApp(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.setWindowTitle('QMessageBox')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def closeEvent(self, event):

        reply = QMessageBox.question(self, 'Message', 'Are you sure to quit?',
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Now when you close the window, a message box will appear to confirm your actino.


Description

When you close QWidget, QCloseEvent is created and sent to the widget.

To edit the widget’s actions, you need to edit closeEvent() event handler.


reply = QMessageBox.question(self, 'Message', 'Are you sure to quit?',
                             QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

The second parameter enters the strings on the title bar(‘Message’), and the third parameter enters the strings to be shown on the dialog(‘Are you sure to quit?’).

The fourth decides the type of button to be shown on the dialog, and finally, the default button.

If you set it as QMessageBox.No, the ‘No’ button is selected when the message box appears.

The restore value is saved in reply variable.


if reply == QMessageBox.Yes:
    event.accept()
else:
    event.ignore()

If you click the ‘Yes’ button, the event is accepted and the widget is closed.

If you click the ‘No’ button, the event is ignored and the widget does not close.


Results

../_images/5_5_qmessagebox.png

Figure 6-5. Message box.

Prev/Next