Preventing PyQt to silence exceptions occurring in slots

前端 未结 3 1900
说谎
说谎 2020-11-29 02:59

As far as I can see, if an exception occurs in a slot under PyQt, the exception is printed to screen, but not bubbled. This creates a problem in my testing strategy, because

3条回答
  •  醉话见心
    2020-11-29 03:21

    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 PyQt4 import QtGui, QtCore
    
    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(QtGui.QPushButton):
        def __init__(self, parent=None):
            QtGui.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(QtGui.QApplication):
        def notify(self, obj, event):
            isex = False
            try:
                return QtGui.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"
    

提交回复
热议问题