# 多线程实例3 method = [RTYtrend,OTDTrend,DDHTrend,PROTrend,Show_s,Show_q,Show_d,Show_i,Show_p,Show_allongoing,Show_status, s_daily,q_daily,d_daily,i_daily,p_daily] with ThreadPoolExecutor(max_workers=50) as executor: for i in range(len(method)): executor.submit(method[i])报警:QObject: Cannot create children for a parent that is in a different thread. (Parent is QApplication(0x150ecd56550), parent's thread is QThread(0x150d9a50d30), current thread is QThread(0x150ed1b6fd0)怎么解决,代码演示
时间: 2024-03-27 08:41:36 浏览: 156
您可以通过将每个方法的代码放入一个单独的子线程中来解决此问题,并确保子线程中的所有QObject对象都是在该子线程中创建的。以下是示例代码:
```python
from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
class Worker(QObject):
finished = pyqtSignal()
@pyqtSlot()
def RTYtrend(self):
# RTYtrend code here
self.finished.emit()
@pyqtSlot()
def OTDTrend(self):
# OTDTrend code here
self.finished.emit()
# Define other methods here
if __name__ == '__main__':
app = QApplication(sys.argv)
thread = QThread()
worker = Worker()
# Move the worker object to the thread
worker.moveToThread(thread)
# Connect the finished signal to the thread's quit method
worker.finished.connect(thread.quit)
# Start the thread
thread.start()
# Call the methods in the worker object
thread.started.connect(worker.RTYtrend)
thread.started.connect(worker.OTDTrend)
# Call other methods here
# Wait for the thread to finish
thread.finished.connect(app.exit)
sys.exit(app.exec_())
```
在上面的示例代码中,我们创建了一个名为Worker的QObject子类,并在其中定义了一些方法。我们将每个方法定义为一个pyqtSlot,并在其中放置实际的代码。我们还定义了一个finished信号,当每个方法完成时将发出该信号。
在main函数中,我们创建了一个QThread对象和一个Worker对象。我们使用worker.moveToThread(thread)将Worker对象移动到新线程中。我们还将worker.finished信号连接到thread.quit方法,以便在每个方法完成时退出线程。
在主线程中,我们调用thread.started.connect(worker.method)来启动每个方法。请注意,我们不直接调用方法,而是连接到线程的started信号上,以便在子线程中运行方法。
最后,我们连接thread.finished信号到app.exit方法,以确保当所有方法完成并退出线程后,应用程序能够正常退出。
阅读全文