Skip to content Skip to sidebar Skip to footer

Qthreading Pyqtgraph Plotwidgets In Pyqt4

As a continuation of the question I got solved here some days ago, I've got a PyQt4 GUI which embeds two PyQtGraph's PlotWidgets, which each set/update data from an threaded random

Solution 1:

You need to keep the GUI and the thread separate. They must not share any GUI object like the plot widget in this case!

I'm not sure if you need threading since your data is not very big and is only updated 10 times a second. But if you decide to use it, only use signals and slots to communicate between thread and GUI.


Below is a modified version of your program which uses threading and works fine. It uses the new style signals and slots. This is hopefully easier to understand, because you can just use object as datatype.

Two things hat make no sense in your program are:

  • you redefine self.curve in the plotting slot.
  • you call the plotting slot when pressing the button. Instead a button press should start the thread.

I have corrected them.

import random
import sys
import pyqtgraph as pg
import time
from PyQt4 import QtGui, QtCore


classMyThread(QtCore.QThread):
    signal = QtCore.pyqtSignal(object)
    def__init__(self, parent=None):
        super(MyThread, self).__init__(parent=parent)
        self.data = [0]

    def__del__(self):
        self.exiting = True
        self.wait()

    defrun(self):
        whileTrue:
            self.data.append(random.random())
            self.signal.emit(self.data)
            time.sleep(0.1)


classLoginWidget(QtGui.QWidget):
    def__init__(self, parent=None):
        super(LoginWidget, self).__init__(parent)
        self.myThread = MyThread()
        layout = QtGui.QHBoxLayout()
        self.button = QtGui.QPushButton('Start Plotting')
        layout.addWidget(self.button)
        self.plot = pg.PlotWidget()
        layout.addWidget(self.plot)
        self.setLayout(layout)
        self.curve = self.plot.getPlotItem().plot()
        self.button.clicked.connect(self.start)


    defplotter(self, data):
        self.curve.setData(data)

    defstart(self):
        self.myThread.start()
        self.myThread.signal.connect(self.plotter)


classMainWindow(QtGui.QMainWindow):
    def__init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.centralwidget = QtGui.QWidget(self)
        self.setCentralWidget(self.centralwidget)
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.login_widget_1 = LoginWidget(self)
        self.horizontalLayout.addWidget(self.login_widget_1)
        self.login_widget_2 = LoginWidget(self)
        self.horizontalLayout.addWidget(self.login_widget_2)
        self.setCentralWidget(self.centralwidget)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Post a Comment for "Qthreading Pyqtgraph Plotwidgets In Pyqt4"