如何通过信号传递对象参数

时间:2016-05-26 02:06:12

标签: python qt pyqt signals

是否可以将point对象作为参数传递给run函数?以下代码会导致TypeError: signal() only accepts 0 arguments, 2 given!

import PySide.QtCore as QtCore

def run(arg = None, *args, **kwargs):
    print 'run:', arg, args, kwargs

class Emitter(QtCore.QObject):
    signal = QtCore.Signal()

emitter = Emitter()
emitter.signal.connect(run)

point = QtCore.QPoint()
emitter.signal.emit(point)

2 个答案:

答案 0 :(得分:1)

您必须指定要发送的对象的类型。例如,传递带信号的int。

def Emitter(QtCore.QObject):
    signal = QtCore.Signal(int)

我建议阅读更多有关此内容的文档。例如,https://wiki.qt.io/Signals_and_Slots_in_PySide

答案 1 :(得分:0)

方法1.0: 在声明object时指定signal = QtCore.Signal(object)作为类型:

import PySide.QtCore as QtCore

def run(arg = None, *args, **kwargs):
    print 'run:', arg, args, kwargs

class Emitter(QtCore.QObject):
    signal = QtCore.Signal(object) 

emitter = Emitter()
emitter.signal.connect(run)

point = QtCore.QPoint()

emitter.signal.emit(point)

方法1.1:使用相同的方法传递多个参数:

import PySide.QtCore as QtCore

def run(arg = None, *args, **kwargs):
    print 'run:', arg, args, kwargs

class Emitter(QtCore.QObject):
    signal = QtCore.Signal(object, object, str, int, dict, list, tuple) 

emitter = Emitter()
emitter.signal.connect(run)

point = QtCore.QPoint()
point2 = QtCore.QPoint()
emitter.signal.emit(point, point2, 'foo', 10, {1:'one'}, [1,2], (1, 2))

方法2:

在声明tuple时指定类型signal

 signal = QtCore.Signal(tuple)

所有传递的参数后面都应加一个逗号:...emit(point,)

import PySide.QtCore as QtCore

def run(arg = None, *args, **kwargs):
    print 'run:', arg, args, kwargs

class Emitter(QtCore.QObject):
    signal = QtCore.Signal(tuple) 

emitter = Emitter()
emitter.signal.connect(run)

point = QtCore.QPoint()

emitter.signal.emit(point,)