我正在尝试使用 PyQt5 编写一个在系统托盘中工作的应用程序。代码有时会引发异常,我需要能够捕获它们。
我希望当应用程序中发生异常时,主事件循环会退出,因此像这样捕获它应该可以工作:
try:
application.exec()
except:
do_stuff()
Run Code Online (Sandbox Code Playgroud)
在下面的例子中,当我按下“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!")
Run Code Online (Sandbox Code Playgroud)
有 2 个类似的问题,但那里的答案没有做我需要做的: …