【发布时间】:2020-10-23 13:23:45
【问题描述】:
我一直在尝试使用concurrent.futures.ThreadPoolExecutor() 在我的应用程序中运行一些后台任务,以便在这些任务(“测量”)运行时能够与 GUI 交互。完成这些任务后,我分配一个回调函数来更新 GUI 的某些字段,然后尝试根据这些字段更新 GUI 小部件(绘图、表格、列表等)。
这是一个例子:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
*some more code goes here*
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
def perform_measurement():
future = self.executor.submit(*a function*)
future.add_done_callback(self.update_gui_fields)
def update_gui_fields(self, future):
data = future.result()
self.items_for_list.append(QStandardItem(data['key']))
*more fields are updated here*
self.QListView1.setModel(self.items_for_list)
*more widgets are updated here*
问题是字段更新正常,但是当我尝试与小部件交互时,应用程序崩溃了。这是因为子代(此处为self.items_for_list)与父代(此处为self.QListView1)处于不同的线程中。这是我得到的错误:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QListView(0x555795efbc10), parent's thread is QThread(0x555795296600), current thread is QThread(0x7fd12400a100)
QBasicTimer::start: QBasicTimer can only be used with threads started with QThread
我在以前的帖子中找不到任何解决方案。知道如何攻击这个吗? 谢谢!
【问题讨论】:
-
您应该使用 Qt 线程而不是 Python 线程。看看there 它的一般工作原理和/或搜索所以有很多类似的问题......
标签: python pyqt5 qthread threadpoolexecutor