PyQt QMessageBox, you can use to create dialogs. This is a little popup window that you’ve often seen on your desktop.

It may be a single line message, an “are you sure you want to save?” message or something more advanced.

This messagebox supports all kinds of variations and buttons. In this lesson you’ll learn how to create a information dialog window.

Related Course: Create GUI Apps with Python PyQt5

Dialog

Initial window

Create a window with a button. If you click the button, the dialog will popup.

(This is also where PyQt gets initialized.)

1
2
3
4
5
6
7
8
9
10
11
def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50,50)
button1.clicked.connect(showDialog)
win.setWindowTitle("Click button")
win.show()
sys.exit(app.exec_())

So lets take a look at showDialog().

Create a dialog

A dialog is created with QMessageBox(). Don’t forget to import this from PyQt5.

1
from PyQt5.QtWidgets import QPushButton

Then use the methods setIcon(), setText(), setWindowTitle() to set the window decoration.

You can configure the dialogs buttons with setStandardButtons().

1
2
3
4
5
6
7
8
9
10
11
12
def showDialog():
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Message box pop up window")
msgBox.setWindowTitle("QMessageBox Example")
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.buttonClicked.connect(msgButtonClick)

returnValue = msgBox.exec()
if returnValue == QMessageBox.Ok:
print('OK clicked')

pyqt messagebox

Downloadable code

You can copy and paste the code below on your own computer, to test how it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

def window():
app = QApplication(sys.argv)
win = QWidget()
button1 = QPushButton(win)
button1.setText("Show dialog!")
button1.move(50,50)
button1.clicked.connect(showDialog)
win.setWindowTitle("Click button")
win.show()
sys.exit(app.exec_())

def showDialog():
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText("Message box pop up window")
msgBox.setWindowTitle("QMessageBox Example")
msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
msgBox.buttonClicked.connect(msgButtonClick)

returnValue = msgBox.exec()
if returnValue == QMessageBox.Ok:
print('OK clicked')

def msgButtonClick(i):
print("Button clicked is:",i.text())

if __name__ == '__main__':
window()

If you are new to Python PyQt, then I highly recommend this book.

Download Examples