使用重载的PySide信号调用Python函数,而不传递参数



我正试图以不同的方式从线程工作者调用PySide应用程序中的同一函数。用test_sig = Signal((), (int,), (str,))重载PySide信号,为测试函数提供三个插槽(@Slot()@Slot(int)@Slot(str)(,然后发射每个信号(test_sig.emit()test_sig[int].emit(1)test_sig[str].emit('a')(适用于整数和字符串情况。但是,无论我尝试什么,我都无法在没有通过参数的情况下调用测试函数。

根据我的尝试,当信号过载时,发射test_sig.emit()似乎不会立即发射。只有当下一个定义的过载信号中的第一个(在我的情况下是[str](发出时,它才会发出两次

我使用的是Python 3.9和PySide==1.15.1。以下是我的最小工作示例:

import sys
from PySide2.QtCore import QRunnable, QObject, QThreadPool, Slot, Signal
from PySide2.QtWidgets import QApplication, QMainWindow

# Signals class
class WorkerSignals(QObject):
test_sig = Signal((), (str,), (int,))
finished = Signal()

# Test worker
class Worker(QRunnable):
def __init__(self):
super().__init__()
self.signals = WorkerSignals()
@Slot()
def run(self):
self.signals.test_sig.emit()  # Trying to call function with no args
self.signals.test_sig[int].emit(1)  # Call function with int
self.signals.test_sig[str].emit('a')  # Call function with str
self.signals.finished.emit()

class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.threadpool = QThreadPool()
self.run_test()
def run_test(self):
worker = Worker()
worker.signals.test_sig.connect(self.test_func)  # I suspect this might be what I'm doing wrong
worker.signals.test_sig[int].connect(self.test_func)
worker.signals.test_sig[str].connect(self.test_func)
worker.signals.finished.connect(self.test_finished)
self.threadpool.start(worker)
@Slot()
@Slot(int)
@Slot(str)
def test_func(self, arg=None):
test_result = 'Test reached'
if arg:
test_result += f', arg received and is a {type(arg)}.'
else:
test_result += ' and no arg received.'
print(test_result)
@Slot()
def test_finished(self):
self.close()

if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())

其终端输出为:

Test reached, arg received and is a <class 'int'>.
Test reached, arg received and is a <class 'str'>.
Test reached, arg received and is a <class 'str'>.

我找到的唯一解决方法是用test_sig = Signal((int,), (str,))过载信号,用test_sig.emit(None)发射,而不连接test_sig.connect()信号,这会导致以下终端输出:

Test reached and no arg received.
Test reached, arg received and is a <class 'int'>.
Test reached, arg received and is a <class 'str'>.

这显然是一个错误。使得Signal除了不消除先前信息的缓冲之外,不允许在没有自变量的情况下建立过载信号。

另一方面,在pyqt5中,可以观察到预期的行为,因此我们可以指出它不是qt错误,而只是pyside2。

我已经创建了PYSIDE-1427错误。

最新更新