問題描述
我想在我的 PyQt5 應(yīng)用程序中使用裝飾器來處理異常:
I wanted to use a decorator to handle exceptions in my PyQt5 application:
def handle_exceptions(func):
def func_wrapper(*args, **kwargs):
try:
print(args)
return func(*args, **kwargs)
except Exception as e:
print(e)
return None
return func_wrapper
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
loadUi("main_window.ui",self)
self.connect_signals()
def connect_signals(self):
self.menu_action.triggered.connect(self.fun)
@handle_exceptions
def fun(self):
print("hello there!")
運行時出現(xiàn)以下異常:
fun() takes 1 positional argument but 2 were given
輸出為 False
(在裝飾器中打印 args).
The output is False
(printed args in the decorator).
有趣的是,當我在構(gòu)造函數(shù)中直接通過 self.fun()
運行 fun()
函數(shù)或注釋裝飾器時,一切正常.似乎裝飾器添加了一個額外的參數(shù),但僅在信號調(diào)用函數(shù)時.怎么回事?
The interesting thing is that when I run the fun()
function directly by self.fun()
in the constructor or comment the decorator, everything works. Seems like the decorator adds an additional argument, but only when the function is called by the signal. What is going on?
推薦答案
問題是因為triggered
信號超載,也就是說它有2個簽名:
The problem is caused because the triggered
signal is overload, that is to say it has 2 signatures:
void QAction::triggered(bool checked = false)
QAction.triggered()
QAction.triggered(bool checked)
所以默認情況下它會發(fā)送一個 boolean(false) 顯然不接受導致錯誤的有趣"方法.
So by default it sends a boolean(false) that clearly does not accept the "fun" method causing the error.
在這種情況下,解決方案是使用 @pyqtSlot()
裝飾器來指明你必須接受的簽名:
In this case the solution is to use the @pyqtSlot()
decorator to indicate the signature that you must accept:
@pyqtSlot()
@handle_exceptions
def fun(self):
print("hello there!")
這篇關(guān)于裝飾器添加了一個意想不到的參數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!