Using QMessageBox in PyQt5 – Tutorial #16

Posted by

PyQt5 Tutorial #16 – Working with QMessageBox

PyQt5 Tutorial #16 – Working with QMessageBox

Welcome to tutorial #16 of our PyQt5 series. In this tutorial, we will learn how to work with QMessageBox in PyQt5. QMessageBox is a pre-built dialog box that allows you to display a message to the user and get their response. This can be useful for displaying warnings, errors, or asking for confirmation from the user.

Creating a Simple Message Box

To create a simple message box, you can use the QMessageBox class and call the exec() method to display it. Here’s an example:

“`python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox

class App(QMainWindow):
def __init__(self):
super().__init__()

self.setWindowTitle(‘PyQt5 QMessageBox Example’)
self.setGeometry(100, 100, 300, 200)

button = QPushButton(‘Click me’, self)
button.clicked.connect(self.show_message_box)

def show_message_box(self):
message_box = QMessageBox()
message_box.setIcon(QMessageBox.Information)
message_box.setText(‘Hello, this is a message box!’)
message_box.setWindowTitle(‘Message Box Example’)
message_box.exec()

if __name__ == ‘__main__’:
app = QApplication(sys.argv)
window = App()
window.show()
sys.exit(app.exec_())
“`

In this example, we create a simple window with a button. When the button is clicked, it triggers the show_message_box() method, which creates and displays a QMessageBox with the text “Hello, this is a message box!”. It also sets the icon and title of the message box.

Handling User Response

After displaying the message box, you may want to handle the user’s response. You can use the QMessageBox.information(), QMessageBox.question(), QMessageBox.warning(), or QMessageBox.critical() methods to display different types of message boxes to the user. Each method returns a standard button value, which you can use to determine the user’s choice. Here’s an example:

“`python
def show_message_box(self):
message_box = QMessageBox()
message_box.setIcon(QMessageBox.Question)
message_box.setText(‘Do you want to save your changes?’)
message_box.setWindowTitle(‘Save Changes’)
message_box.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)

response = message_box.exec()

if response == QMessageBox.Save:
print(‘Changes saved’)
elif response == QMessageBox.Discard:
print(‘Changes discarded’)
elif response == QMessageBox.Cancel:
print(‘Action canceled’)
“`

In this example, we create a message box with a question icon, asking the user if they want to save their changes. We set the standard buttons to Save, Discard, and Cancel. When the user makes a choice, the value of the response variable is used to determine which action to take.

That’s it for this tutorial! You now know how to work with QMessageBox in PyQt5. You can use it to display informative messages, warnings, errors, and ask for user confirmation.