Skip to content

Instantly share code, notes, and snippets.

@ialexpovad
Created December 1, 2022 06:35
Show Gist options
  • Save ialexpovad/2c49a85970b99e32cd277f7703214469 to your computer and use it in GitHub Desktop.
Save ialexpovad/2c49a85970b99e32cd277f7703214469 to your computer and use it in GitHub Desktop.
[Preventing PyQt to silence exceptions occurring in slots] +100 Can create a decorator that wraps PyQt' new signal/slot decorators and provides exception handling for all slots. Can also override QApplication::notify to catch uncaught C++ exceptions.
import sys
import traceback
import types
from functools import wraps
from PyQt5 import QtGui, QtCore, QtWidgets
def MyPyQtSlot(*args):
if len(args) == 0 or isinstance(args[0], types.FunctionType):
args = []
@QtCore.pyqtSlot(*args)
def slotdecorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args)
except:
print ("Uncaught Exception in slot")
traceback.print_exc()
return wrapper
return slotdecorator
class Test(QtWidgets.QPushButton):
def __init__(self, parent=None):
QtWidgets.QWidget.__init__(self, parent)
self.setText("hello")
self.clicked.connect(self.buttonClicked)
@MyPyQtSlot("bool")
def buttonClicked(self, checked):
print ("clicked")
raise Exception("wow")
class MyApp(QtWidgets.QApplication):
def notify(self, obj, event):
isex = False
try:
return QtWidgets.QApplication.notify(self, obj, event)
except Exception:
isex = True
print ("Unexpected Error")
print (traceback.format_exception(*sys.exc_info()))
return False
finally:
if isex:
self.quit()
app = MyApp(sys.argv)
t=Test()
t.show()
try:
app.exec_()
except:
print ("exiting")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment