python logo

qt message box


Python hosting: Host, run, and code Python in the cloud!

PyQT4 offers message box functionality using several functions.
Messageboxes included in PyQT4 are: question, warning, error, information, criticial and about box.

Related course: Create GUI Apps with Python PyQt5

PyQt4 mesagebox

The code below will display a message box with two buttons:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
import sys
from PyQt4.QtGui import *

# Create an PyQT4 application object.
a = QApplication(sys.argv)

# The QWidget widget is the base class of all user interface objects in PyQt4.
w = QWidget()

# Show a message box
result = QMessageBox.question(w, 'Message', "Do you like Python?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

if result == QMessageBox.Yes:
print('Yes.')
else:
print('No.')

# Show window
w.show()

sys.exit(a.exec_())

Result:

qtMessagebox question qtMessagebox question

There are different types of messageboxes that PyQT4 provides.

PyQT4 Warning Box


You can display a warning box using this line of code:

QMessageBox.warning(w, "Message", "Are you sure you want to continue?")

PyQT4 Information box


We can display an information box using QMessageBox.information()

QMessageBox.information(w, "Message", "An information messagebox @ pythonspot.com ")

Result:

QMessageBox Info QMessageBox Info

PyQT4 Critical Box


If something goes wrong in your application you may want to display an error message.

QMessageBox.critical(w, "Message", "No disk space left on device.")



Result:

QMessagebox QMessagebox

PyQT4 About box


We have shown the question box above.

QMessageBox.about(w, "About", "An example messagebox @ pythonspot.com ")



Result:

qt Messagebox qt Messagebox

Download PyQT Code (Bulk Collection)

BackNext





Leave a Reply:




Daryl Lee Fri, 29 Jan 2016

A) Thanks for the tutorial--it seems to be just what I need. But ...
B) On this step, I get this when I click either button:
2016-01-29 10:06:36.513 python3[75552:9158619] modalSession has been exited prematurely - check for a reentrant call to endModalSession:
At that point the window size increases, goes blank, and wait for me to dismiss the window.

I'm running Python 3.4.4 :: Anaconda 2.4.1 (x86_64), and have made the necessary changes to 'print'. Except for this behavior, the tutorials have run exactly as expected.

Any ideas on what's going on and how to fix it?

Frank Sat, 30 Jan 2016

Are you running OS X? It seems to be an OS X specific bug: https://forum.qt.io/topic/4...