I created a widget, which contains a method will start an another thread.
When I tried to connect the thread's started signal to a lambda function, it failed.
Actually, the thread has a ThreadId as same as Application instance. But when I tried to connect it to a non-lambda function, it works normally.
So, what should I do to connect to a function which requires parameters?
Here is my code:
from PyQt6.QtWidgets import QLabel, QApplication, QHBoxLayout, QPushButton, QWidget
from PyQt6.QtCore import pyqtSignal, QObject, QThread
import time
import sys
class Worker(QObject):
send = pyqtSignal(str)
finished = pyqtSignal()
def __init__(self) -> None:
super().__init__()
def run(self, stop = 5):
print(f"Worker thread: {int(self.thread().currentThreadId())}")
for i in range(stop):
time.sleep(1)
self.send.emit(str(i))
self.finished.emit()
def runNoParam(self):
print(f"Worker thread: {int(self.thread().currentThreadId())}")
for i in range(5):
time.sleep(1)
self.send.emit(str(i))
self.finished.emit()
class Window(QWidget):
def __init__(self) -> None:
super().__init__()
layout = QHBoxLayout()
self.label = QLabel("number")
self.btn = QPushButton("click me")
layout.addWidget(self.label)
layout.addWidget(self.btn)
self.setLayout(layout)
self.btn.clicked.connect(self.test)
def test(self):
self.threader = QThread()
self.worker = Worker()
self.worker.moveToThread(self.threader)
# connect to a lambda funcion, work failed!
self.threader.started.connect(lambda: self.worker.run())
# connect to a non-lambda function, work normally!
# self.threader.started.connect(self.worker.runNoParam)
self.worker.send.connect(lambda s: self.label.setText(s))
self.worker.finished.connect(self.threader.quit)
self.worker.finished.connect(self.threader.deleteLater)
self.threader.start()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Window()
win.show()
print(f"Application thread: {int(QApplication.instance().thread().currentThreadId())}")
sys.exit(app.exec())