问题描述
据我所知,如果在 PyQt 下的插槽中发生异常,则该异常会打印到屏幕上,但不会冒泡.这在我的测试策略中产生了问题,因为如果插槽中发生异常,我不会看到测试失败.
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 if an exception occurs in a slot, I will not see the test fail.
这是一个例子:
import sys
from PyQt4 import QtGui, QtCore
class Test(QtGui.QPushButton):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setText("hello")
self.connect(self, QtCore.SIGNAL("clicked()"), self.buttonClicked)
def buttonClicked(self):
print "clicked"
raise Exception("wow")
app=QtGui.QApplication(sys.argv)
t=Test()
t.show()
try:
app.exec_()
except:
print "exiting"
注意异常如何永远不会退出程序.
Note how the exception never quits the program.
有没有办法解决这个问题?
Is there a way to work around this problem?
推荐答案
可以创建一个装饰器,包装 PyQt 的新信号/槽装饰器,并为所有槽提供异常处理.还可以覆盖 QApplication::notify 以捕获未捕获的 C++ 异常.
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"
这篇关于防止 PyQt 使插槽中发生的异常静音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!