PySide * any *方法调用-信号和插槽

时间:2018-12-24 06:06:47

标签: python pyside

我正在尝试为我的PySide GUI库创建简单的通用方法调用:

null

插槽以获取对象,方法并使用 args 调用 object.method

foo

这应该发出那个棘手的位置:

undefined

这是另一个工作线程,例如,更新进度条

class GUI(QApplication):
    def __init__(self, *args, **kwargs):
        super(GUI, self).__init__()
        self.gui_signal = Signal()
        self.gui_signal.connect(self.method_call)

我看到这种方法行不通,并且args传递的方式错误。我该怎么办?

1 个答案:

答案 0 :(得分:1)

信号不应定义为类的成员,而应定义为类的属性。另一方面,您必须指示签名,最后,字典不支持,因此您必须将*args**kwargs转换为元组。

from PySide import QtCore, QtGui

class GUI(QtGui.QApplication):
    gui_signal = QtCore.Signal(object, str, tuple)

    def __init__(self, *args, **kwargs):
        super(GUI, self).__init__([])
        self.gui_signal.connect(self.method_call)

    @QtCore.Slot(object, str, tuple)
    def method_call(self, obj, method_name, data):
        if hasattr(obj, method_name):
            method = getattr(obj, method_name)
            args, kwargs = data
            if hasattr(method, '__call__'):
                method(*args, **kwargs)

    def anymethod(self, obj, method_name, *args, **kwargs):
        self.gui_signal.emit(obj, method_name, (args, kwargs))

class MyApp(object):
    def __init__(self):
        self.gui = GUI()

        self.progressBar = QtGui.QProgressBar(maximum=100)
        self.progressBar.show()

        self.total = 200
        self.done = 100
        QtCore.QTimer.singleShot(300, self.update_progress)

    def update_progress(self):
        perc = (self.done * 100) / self.total
        self.gui.anymethod(self.progressBar, 'setValue', int(perc))

    def run(self):
        return self.gui.exec_()

if __name__ == '__main__':
    import sys
    app = MyApp()
    sys.exit(app.run())