[PyQt] Multi-threading and live-plotting software.

Fabien Lafont lafont.fabien at gmail.com
Tue Feb 28 12:12:07 GMT 2012


Hello everyone,

I'm trying to plot live data. I manage to do it but the only problem
is it's a bit laggy because I'm comunicating with devices and it takes
few seconds to receive the datas. During this delay the plot
(matplotlib) is not responsive, and it's a bit problematic for my
application. So I'm trying to switch to a threaded soft.

How can I update my graph using a thread and do another (longer)
operation at the same time?

I've tried to write this simple code but it doesn't work... You will
directly see that I'm a beginner :)

from PyQt4 import QtCore, QtGui
import time
import sys
import random
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class Graph(FigureCanvas):
    """Matplotlib Figure widget"""
    def __init__(self):

        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.updateGeometry(self)
        # generates first "empty" plots
        self.user = []
        self.l_user, = self.ax.plot([], self.user)

        self.fig.canvas.draw()

        self.get_number()


    def get_number(self):
        self.result1 = random.randint(0,4)
        self.user.append(self.result1)
        time.sleep(0.5)
        self.get_number()


class AThread(QtCore.QThread):

    def run(self):
        time.sleep(1)
        plot.l_user.set_data(len(self.user), self.user)
        plot.fig.canvas.draw()
        FigureCanvas.updateGeometry(self)

def usingQThread():
    app = QtCore.QCoreApplication([])
    qApp = QtGui.QApplication(sys.argv)
    plot = Graph()
    thread = AThread()
    thread.finished.connect(app.exit)
    thread.start()
    sys.exit(app.exec_())

Thanks!

Fab


More information about the PyQt mailing list