插槽上的装饰器(PyQt)

时间:2018-05-08 12:03:38

标签: python pyqt pyqt5 decorator qt-signals

我使用QT来构建我的GUI,并使用装饰器来记录日志。当我在插槽上使用装饰器时,GUI会崩溃。

代码是:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


def LogInfos(func):

    def wrapper(*s, **gs):
        print('log')
        ret = func(*s, **gs)
        return ret

    return wrapper
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QHBoxLayout(self)
        btn = QPushButton('test')
        layout.addWidget(btn)
        btn.clicked.connect(self.testSlot)

    @LogInfos
    def testSlot(self):
        print('test slot')


@LogInfos
def testLog():
    print('test log')

if __name__ == '__main__':

    testLog()

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

我已经测试过装饰器功能没问题,删除装饰器后GUI就可以了。

2 个答案:

答案 0 :(得分:1)

请参阅@ ekhumoro对原因的解释,但使用插槽中的修饰方法会因签名错误而导致问题。

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


def LogInfos(func):

    def wrapper(*s, **gs):
        print('log')
        ret = func(*s, **gs)
        return ret

    return wrapper
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QHBoxLayout(self)
        btn = QPushButton('test')
        layout.addWidget(btn)
        btn.clicked.connect(self.testSlot)

    @LogInfos
    def testSlot(self, checked=False):
        print('test slot')


@LogInfos
def testLog():
    print('test log')

if __name__ == '__main__':

    testLog()

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

试一试:btn.clicked.connect(lambda:self.testSlot())

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


def LogInfos(func):

    def wrapper(*s, **gs):
        print('log')
        ret = func(*s, **gs)
        return ret

    return wrapper
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QHBoxLayout(self)
        btn = QPushButton('test')
        layout.addWidget(btn)
        #btn.clicked.connect(self.testSlot)
        btn.clicked.connect(lambda: self.testSlot())         

    @LogInfos
    def testSlot(self):
        print('test slot')


@LogInfos
def testLog():
    print('test log')

if __name__ == '__main__':

    testLog()

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

enter image description here