【发布时间】:2019-07-24 12:08:43
【问题描述】:
这有点长,第一部分只是对问题的描述,第二部分是我的“修复”是否正确的问题。
我从 python 编程开始。我创建了一个程序,它与读取我们熔化实验室熔炉温度的 Arduino 进行通信。然后在 PID 算法中使用温度,并将输出设置为 Arduino。通信是通过 pyserial 完成的。到目前为止,一切都有效,包括实时绘制温度信号、PID 变量等。该脚本包括一个主循环和 3 个线程(串行通信、一个从串行端口读取的数据移位器、来自 QWidget 的设定温度和 PID 算法的输出。这些值用于创建一个数组以在 pyqtgraph 中显示。最后,第三个线程将数据从 datashifter 转移到 QWidget。
当使用我的 Linux 笔记本时,一切正常,并且 GUI 从未停止更新。相比之下,当使用任何 Windows 主机时,我会遇到一些 pyqtgraphs 停止刷新的问题。这种行为很奇怪,因为我或多或少地同时设置了所有数据,使用相同的 numpy 数组(只是不同的列) - 有些图刷新时间更长(小时),有些更早停止(分钟)。在搜索了或多或少的漏洞之后 ;-) 我认为我发现了问题:它是从线程到 GUI 的数据传递。一些虚拟代码来解释发生了什么:
DataUpdaterToGUI(QThread):
#sets the QWidget from main loop
def setGUI(self, gui):
self.gui = gui
def run()
while True:
with lock(): # RLock() Instance
copyArray = self.dataArray[:] # copy the array from the shifter
self.gui.plot1.copyArray(dataArray[:, 0], copyArray[:, 1])
self.gui.plot2.copyArray(dataArray[:, 0], copyArray[:, 2])
# self.gui.update()
# QApplication.instance().processEvents()
调用 self.gui.update() 和 processEvents() 都不会对结果产生任何影响:绘图会在一段时间后停止重绘(在 Windows 上)。
现在我有一个非常简单的例子,只是想确定我是否正确使用了线程。它工作正常,但我有一些问题:
- 信号槽方法是否复制传递的数据?
- 为什么不需要调用QWidget的update()方法?
- 使用信号时是否必须使用任何类型的锁?
class Main(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout(self)
self.graph = pg.PlotWidget()
self.graph.setYRange(0,1000)
self.plot = self.graph.plot()
self.layout.addWidget(self.graph,0,0)
self.show()
def make_connection(self, data_object):
data_object.signal.connect(self.grab_data)
@pyqtSlot(object)
def grab_data(self, data):
print(data)
self.plot.setData(data)
class Worker(QThread):
signal = pyqtSignal(object)
def __init__(self):
super().__init__()
def run(self):
self.data = [0, 1]
i = 2
while True:
self.data[1] = i
self.signal.emit(self.data)
time.sleep(0.01)
i += 1
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Main()
worker = Worker()
widget.make_connection(worker)
worker.start()
sys.exit(app.exec_())
【问题讨论】:
标签: python multithreading plot pyqt5 pyqtgraph