Error message context manager#
superqt.utils.exceptions_as_dialog
#
Bases: AbstractContextManager
Context manager that shows a dialog when an exception is raised.
See examples below for common usage patterns.
To determine whether an exception was raised or not, check the exception
attribute after the context manager has exited. If use_error_message
is False
(the default), you can also access the dialog
attribute to get/manipulate the
QMessageBox
instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
exceptions |
type[BaseException] | tuple[type[BaseException], ...]
|
The exception(s) to catch, by default |
Exception
|
icon |
Icon
|
The icon to show in the QMessageBox, by default |
Critical
|
title |
str
|
The title of the |
'An error occurred'
|
msg_template |
str
|
The message to show in the
The default template is the content of the exception: |
'{exc_value}'
|
buttons |
StandardButton
|
The buttons to show in the |
Ok
|
parent |
QWidget | None
|
The parent widget of the |
None
|
use_error_message |
bool | QErrorMessage
|
Whether to use a |
False
|
Attributes:
Name | Type | Description |
---|---|---|
dialog |
QMessageBox | None
|
The |
exception |
BaseException | None
|
Will hold the exception instance if an exception was raised and caught. |
Examplez#
from qtpy.QtWidgets import QApplication
from superqt.utils import exceptions_as_dialog
app = QApplication([])
with exceptions_as_dialog() as ctx:
raise Exception("This will be caught and shown in a QMessageBox")
# you can access the exception instance here
assert ctx.exception is not None
# with exceptions_as_dialog(ValueError):
# 1 / 0 # ZeroDivisionError is not caught, so this will raise
with exceptions_as_dialog(msg_template="Error: {exc_value}"):
raise Exception("This message will be inserted at 'exc_value'")
for _i in range(3):
with exceptions_as_dialog(AssertionError, use_error_message=True):
assert False, "Uncheck the checkbox to ignore this in the future"
# use ctx.dialog to get the result of the dialog
btns = QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel
with exceptions_as_dialog(buttons=btns) as ctx:
raise Exception("This will be caught and shown in a QMessageBox")
print(ctx.dialog.result()) # prints which button was clicked
app.exec() # needed only for the use_error_message example to show