直接从 Qthread PyQt 5 更改 GUI [英] Changing GUI directly from Qthread PyQt 5
问题描述
我已将 GUI 链接发送到我的 Thread 工作线程,并直接从 QThread 更新 GUI 信息.喜欢这里:
Hi i have send to my Thread worker link to GUI and update GUI info directly from QThread. Like here:
class Worker(QThread):
def __init__(self, ui):
QThread.__init__(self)
self.running = False
self.ui = ui
def run(self):
self.running = True
while self.running:
info = self.check_info()
rows = len(info)
self.ui.tableWidget.setRowCount(rows)
self.ui.tableWidget.setColumnCount(6)
...
在主 QMainWindow
我只是添加
def __init__(self, parent=None):
.......
self.myworker = Worker(self.ui)
.....
这样的解决方案在 PyQt5 中是不是很糟糕?我是 PyQt 的新手.谢谢.如果我的解决方案不好,请帮助我修复它.
Is such solution very bad in PyQt5? I am new in PyQt. Thx. If my solution is bad plz help me to fix it.
推荐答案
你不能也不能从辅助线程更新 GUI,你必须通过信号和槽来完成:
You can not and can not update the GUI from a secondary thread, you must do it through signals and slots:
为此,我们将通过 pyqtSignal()
类创建一个信号,我们将指明参数的类型,然后将其连接到我们想要的插槽,如下所示:
For this we are going to create a signal through the class pyqtSignal()
, and we will indicate the types of arguments, then we connect it to the slot that we want, as I show below:
主题:
class Worker(QThread):
list_of_dict_signals = pyqtSignal(list)
str_signal = pyqtSignal(str)
def __init__(self, parent=None):
QThread.__init__(self, parent)
self.running = False
def run(self):
self.running = True
while self.running:
info = self.check_info()
self.list_of_dict_signals.emit(info)
self.str_signal.emit("Requesting info")
界面:
def __init__(self, parent=None):
.......
self.myworker = Worker(self)
self.myworker.list_of_dict_signals.connect(self.onDataFromThread)
self.myworker.str_signal.connect(self.ui.statusbar.showMessage)
self.myworker.start()
def onDataFromThread(self, info):
rows = len(info)
self.ui.tableWidget.setRowCount(rows)
...
这篇关于直接从 Qthread PyQt 5 更改 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!