You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5线程信号传递双参数失败问题求助

PyQt5线程信号传递双参数失败问题求助

嗨,我仔细看了你的代码和遇到的问题,根源其实很明确——槽函数的pyqtSlot装饰器没有和信号的参数类型匹配!

你定义的sendReady信号是QtCore.pyqtSignal(str, bool),传递的是字符串和布尔值两个参数,但你给Worker类里的commData方法加的是@QtCore.pyqtSlot()(没有声明参数类型),这就导致Qt的信号槽机制没法正确识别槽函数的参数要求,调用时自然会报“缺少 positional arguments”的错误。

另外还有个小问题:你给Worker的__init__方法也加了@QtCore.pyqtSlot()装饰器,这个完全没必要,装饰器是给槽函数用的,构造函数不需要加,反而可能引发不必要的问题。

修复后的完整代码

我把需要修改的地方标出来了,你可以直接参考:

#! /usr/bin/python3
from PyQt5 import QtWidgets, QtCore
import sys

# create serial read worker
class Worker(QtCore.QObject):
    # 去掉__init__上多余的@pyqtSlot装饰器
    def __init__(self):
        super(Worker, self).__init__()
        self.working = True

    def work(self):
        if self.working == True:
            # create test increment timer object
            timerT = QtCore.QTimer(self)
            timerT.timeout.connect(self.comms)
            timerT.start(500)

    # 关键修改:给pyqtSlot指定和信号匹配的参数类型(str, bool)
    @QtCore.pyqtSlot(str, bool)
    def commData(self, mes, f):
        print(mes)
        print(f)

    def comms(self):
        pass

# Main Window
class MainWindow(QtWidgets.QMainWindow):
    sendReady = QtCore.pyqtSignal(str, bool)

    def workStart(self):
        self.worker = Worker()
        self.thread = QtCore.QThread()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.work)
        self.sendReady.connect(self.printOut)    # connection ok
        self.sendReady.connect(self.worker.commData) # 现在可以正常传递数据了
        self.thread.start()

    # Start Window
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Auto Watering System')
        self.setMinimumWidth(300)
        self.setMinimumHeight(300)
        self.workStart()
        print("start")
        mes = "99999"
        f = True
        self.sendReady.emit(mes, f)  # connect to pico server

    def printOut(self,mes, f):
        print(mes)
        print(f)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

额外说明

  • 跨线程传递多参数信号时,pyqtSlot必须明确声明参数类型,这样Qt才能正确完成信号和槽的映射
  • 信号的参数类型要和槽函数的参数类型完全一致,不能有类型不匹配的情况
  • 我补全了你代码里缺失的self.worker = Worker()和self.thread = QtCore.QThread(),不然原代码运行会因为未实例化对象报错

你之前尝试的“移动connect位置”“只传一个参数”都没触碰到核心问题,现在修改后应该就能正常传递双参数给线程里的worker了!

备注:内容来源于stack exchange,提问作者JohnPR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 08:50:30