【发布时间】:2019-09-13 02:49:51
【问题描述】:
我正在尝试使用 PyQt5 编写一个在系统托盘中运行的应用程序。 代码有时会引发异常,我需要能够捕获它们。
我希望当应用程序中发生异常时,主事件循环会退出,所以像这样捕获它应该可以工作:
try:
application.exec()
except:
do_stuff()
在下面的例子中,当我按下“Raise”按钮时,我只看到了回溯,但我从来没有看到 error catched! 打印出来。
from PyQt5 import QtWidgets, QtGui, QtCore
class ErrorApp():
def __init__(self):
# Init QApplication, QWidet and QMenu
self.app = QtWidgets.QApplication([])
self.widget = QtWidgets.QWidget()
self.menu = QtWidgets.QMenu("menu", self.widget)
# Add items to menu
self.menu_action_raise = self.menu.addAction("Raise")
self.menu_action_raise.triggered.connect(self.raise_error)
self.menu_action_exit = self.menu.addAction("Exit")
self.menu_action_exit.triggered.connect(self.app.exit)
# Create the tray app
self.tray = QtWidgets.QSystemTrayIcon(QtGui.QIcon("logo.png"), self.widget)
self.tray.setContextMenu(self.menu)
# Show app
self.tray.show()
def raise_error(self):
assert False
e = ErrorApp()
try:
e.app.exec()
except:
print("error catched!")
有 2 个类似的问题,但那里的答案没有做我需要做的事情:
Grab any exception in PyQt: OP 想要监控异常,偶数循环没有退出
Preventing PyQt to silence exceptions occurring in slots:装饰师的回答根本行不通;将sys.exit(1) 添加到sys.excepthook 只会关闭整个程序,而不打印error catched!
【问题讨论】:
标签: python exception pyqt pyqt5