gpt4 book ai didi

python - 将信号从多个工作线程发送到 GUI 线程

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:20 24 4
gpt4 key购买 nike

我有一个带有 24 个文本框的 gui,我想为每个文本框创建一个线程,并使用来自其各自线程的信息更新文本框。

我陷入困境的是从所有线程接收更新 gui 的信号。

代码:

#!/usr/bin/python
# Standard Lib
import logging
import os
import sys
import time
# Third Party
from PyQt4 import QtGui
from PyQt4 import QtCore
# Local Kung Fu
from bin import serial_lib, logger, get_args, utils
from bin.assets.test_suite_gui_form import Ui_MainWindow

class Tester(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
self.color = "RED"
self.status = "Disconnected"

def __del__(self):
self.wait()

def run(self):
self.emit(QtCore.SIGNAL('update(QString)'), "color={} status={}".format(self.color, self.status))
return

class TestSuiteGUI(QtGui.QMainWindow):

def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
# Init class from template
self.ui = Ui_MainWindow()
# Get list of com ports to populate app on init
self.com_ports_list = serial_lib.get_com_ports()
# Build UI
self.ui.setupUi(self)
# Update Labels with COM Ports, where possible, filtered by drivers
self.update_comm_fields(self.com_ports_list)
for num, com_port_chunk in zip(range(1,25), self.com_ports_list):
tester_thread = Tester(com_port_chunk, num)
tester_thread.start()

def update_comm_fields(self, com_ports_list):
for num, port, in zip(range(1, 25), range(0, 24)):
label = getattr(self.ui, 'com_{}'.format(num))
label.setText("COM Port: {}".format(com_ports_list[port]["COM"]))

if __name__ == "__main__":
# Grab args from CLI if necessary
args = get_args.get_args()
# Log file
log_file = os.path.join(utils.app_path, "log", "log.txt")
# Get Logger
logger.get_logger(log_file, verbose=True)
# Init App and display
app = QtGui.QApplication(sys.argv)
test_suite = TestSuiteGUI()
test_suite.show()
# Close app only when window is closed.
sys.exit(app.exec_())

这是正确的方法吗?我尝试使用 QRunnable 和线程池,但在某处读到信号不适用于它。我应该尝试 python 的多线程库作为最后的手段,还是基于事件的系统,因为我需要传递的只是字符串和 bool 值?

最佳答案

您应该像这样定义和发出信号:

class Tester(QtCore.QThread):
updateText = QtCore.pyqtSignal(str)
...
def run(self):
self.updateText.emit("color={} status={}".format(self.color, self.status))

然后您可以像这样连接到信号:

class TestSuiteGUI(QtGui.QMainWindow):
def __init__(self, parent=None):
...
# keep a reference to the threads
self._threads = []
for num, com_port_chunk in zip(range(1,25), self.com_ports_list):
tester_thread = Tester(com_port_chunk, num)
# get a reference to the associated textbox somehow...
textbox = get_the_textbox()
tester_thread.updateText.connect(textbox.setText)
tester_thread.start()
self._threads.append(tester_thread)

显然,这有点粗略,因为不可能实际测试您的示例。

关于python - 将信号从多个工作线程发送到 GUI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36188246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com