PyQt 5-线程绘制2个图形

时间:2018-08-01 16:45:11

标签: python multithreading pyqt5

我无法实时实时绘制我的2张图。我发现,线程可以帮助我解决问题,但是教程对我没有帮助。我希望每个图都有2个线程。在我使用这种格式之前

已从定义应用程序窗口设计中删除

        mf = movefunction(self.main_widget, width=6, height=5, dpi=100)     
        df=distance(self.main_widget, width=6, height=5, dpi=100)

但是程序运行缓慢。所以我想将此功能包装在线程中,但我不知道该怎么做。 我尝试过类似的方法,但这不起作用。

        self.thread1 = QThread()
        self.thread1= movefunction(self.main_widget, width=6, height=5, dpi=100)

        self.thread2 = QThread()
        self.thread2 = distance((self.main_widget, width=6, height=5, dpi=100)

在距离和移动功能内,可以通过串行和绘图获取数据。

Python文件

from __future__ import unicode_literals
import time
import sys
import os
import threading
from queue import Queue
import matplotlib
# Make sure that we are using QT5
matplotlib.use('Qt5Agg')
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import  QLCDNumber, QLabel
from PyQt5.QtCore import QCoreApplication, QObject, QRunnable, QThread, QThreadPool

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import serial
progname = os.path.basename(sys.argv[0])
progversion = "0.1"
ser = serial.Serial('COM3',115200,timeout=0.2)
arduinoData=serial.Serial('COM4',115200)
output=[]
outputy=[]
outputx=[]
outputdx=[]
outputdy=[]
mean10=0
mean5=0
numbers10=0
dxsum=0
XSum=0
dysum=0
YSum=0
class MyMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)


        self.minor=fig.add_subplot(111)
        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self,
        QtWidgets.QSizePolicy.Expanding,
        QtWidgets.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
    def compute_initial_figure(self):
        pass

class movement(MyMplCanvas):
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)

        global t2
        t2= time.time() 
        timer.timeout.connect(self.update_figure)
        timer.start(1)      

    def compute_initial_figure(self):
        self.minor.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
    def update_figure(self):
        print("Start")
        t = time.time() 

        reading=ser.readline().decode("utf-8")

        array=[]

        array=reading.split(",")

        if reading :
            pass
        if not reading:
            array=[0]*21



        elapsedx = time.time() - t
        print("time after spliting ",elapsedx)

        for i in range(len(array)-1):
            array[i] = int(array[i])

        for dx in range(0,20,2):
            outputdx.append(array[dx])
        for dy in range(1,20,2):
            outputdy.append(array[dy])




        last10dx = outputdx[-10:]
        last10dy = outputdy[-10:]           

        print("last10dx: ",last10dx)    
        print("last10dy: ",last10dy)
        sumdx=sum(last10dx)
        sumdy=sum(last10dy)
        global XSum
        XSum=XSum + sumdx
        global YSum
        YSum = YSum + sumdy
        timetocal = time.time() - t
        print("time time to calculate velocity ",timetocal)

        # vel1=(sumdx)/(timetocal)
        # vel1=(vel1)/(0.021166667*1000)# *1000 daje nam m/secc

        # vel2=(sumdy)/(timetocal)
        # vel2=(vel2)/(0.021166667*1000)


        print("veldx" , 0)
        print("vledy", 0)
        print(" sum dx",  sumdx )
        print(" sum dy", sumdy) 
        print("total X", XSum)
        print("total Y", YSum)

        elapsed = time.time() - t
        print("time after summation ",elapsed)

        self.minor.cla()
        self.minor.relim()



        plt.pause(0.000001)     
        if (len(outputdx)>30):
            del outputdx[0:10]
        if (len(outputdy)>30):
            del outputdy[0:10]      
        deltime = time.time() - t
        print("del time  ",deltime)


        lcdx.display(XSum)
        lcdy.display(YSum)
        lcddx.display(sumdx)
        lcddy.display(sumdy)
        lcdvdx.display(0)
        lcdvdy.display(0)
        if abs(XSum) >1200:
            label1200.setText(" Tak " )
            print( t2 -time.time())
        else:
            label1200.setText(" Nie ")

        self.minor.plot(outputdy,  color="red", linewidth=0.5, linestyle="-", label = 'dy')
        self.minor.plot(outputdx,  color="blue", linewidth=0.5, linestyle="-",label='dx')
        self.minor.legend(fontsize=8,loc='upper left', shadow=True,)
        self.minor.set_title('Data from mouse sensor')


        self.draw()
        elapsed5 = time.time() - t
        print("exit time ",elapsed5)



class distance(MyMplCanvas):
#"""A canvas that updates itself every second with a new plot."""
    def __init__(self, *args, **kwargs):
        MyMplCanvas.__init__(self, *args, **kwargs)
        timer = QtCore.QTimer(self)
        t = threading.Thread(target=self.update_figure)
        t.daemon = True
        t.start()

        timer.timeout.connect(self.update_figure)
        timer.start(1)
    def compute_initial_figure(self):
        self.minor.plot([0, 1, 2, 3], [1, 2, 0, 4], 'r')
    def update_figure(self):
        arduinoString=arduinoData.readline()
        str_value = arduinoString.strip()
        if str_value:
            measurement = int(str_value)    
        else:
            measurement = int(0)
        plt.pause(0.000001)     
        self.minor.cla()
        self.minor.set_ylim(0,20)
        output.append(measurement)
        numbers=output[-5:]
        mean5=sum(numbers)/5
        numbers10=output[-10:]
        mean10=sum(numbers10)/10

        if (len(output)>50):
            output.pop(0)
        self.minor.plot( output, color="blue", linewidth=0.5, linestyle="-")
        self.minor.set_title('Sensor distance')
        self.minor.set_xlabel('Time (s)')
        self.minor.set_ylabel('Distance (cm)')
        lcd5.display(mean5)
        lcd10.display(mean10)
        self.draw()

class ApplicationWindow(QtWidgets.QMainWindow):
    def __init__(self):
        global q
        q = Queue()
        run = threading.Event()
        q.join()

        QtWidgets.QMainWindow.__init__(self)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setWindowTitle("application main window")
        self.file_menu = QtWidgets.QMenu('&File', self)
        self.file_menu.addAction('&Quit', self.fileQuit,
        QtCore.Qt.CTRL + QtCore.Qt.Key_Q)

        self.menuBar().addMenu(self.file_menu)
        self.help_menu = QtWidgets.QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.help_menu.addAction('&About', self.about)
        self.main_widget = QtWidgets.QWidget(self)
        self.label = QtWidgets.QLabel()
        self.label.setText("mean from 5 measurement")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.labelm10 = QtWidgets.QLabel()
        self.labelm10.setText("mean from 10 measurement")
        self.labelm10.setAlignment(QtCore.Qt.AlignCenter)
        self.posx=QtWidgets.QLabel()
        self.posx.setText("Position x in total")
        self.posx.setAlignment(QtCore.Qt.AlignCenter)
        posy=QtWidgets.QLabel()
        posy.setText("Position y in total")
        posy.setAlignment(QtCore.Qt.AlignCenter)
        posdx=QtWidgets.QLabel()
        posdx.setText("Position dx")
        posdx.setAlignment(QtCore.Qt.AlignCenter)
        posdy=QtWidgets.QLabel()
        posdy.setText("Position dy")
        posdy.setAlignment(QtCore.Qt.AlignCenter)
        veldx=QtWidgets.QLabel()
        veldx.setText("Velocity in x axis")
        veldx.setAlignment(QtCore.Qt.AlignCenter)
        veldy=QtWidgets.QLabel()
        veldy.setText("Velocity in y axis")
        veldy.setAlignment(QtCore.Qt.AlignCenter)





        # self.setStyleSheet("background-color: rgb(200, 255, 255)")


        global lcd5, lcd10 ,lcdx ,lcdy,lcddx ,lcddy, lcdvdx, lcdvdy ,label1200
        label1200=QtWidgets.QLabel()

        lcd5 =  QLCDNumber(self)
        lcd10 = QLCDNumber(self)
        lcdx=QLCDNumber(self)
        lcdy=QLCDNumber(self)
        lcddx=QLCDNumber(self)
        lcddy=QLCDNumber(self)
        lcdvdx=QLCDNumber(self)
        lcdvdx.setDigitCount(10)
        lcdvdy=QLCDNumber(self)
        lcdvdy.setDigitCount(10)
        lcdarray=[lcd5, lcd10 ,lcdx ,lcdy,lcddx ,lcddy, lcdvdx, lcdvdy]

        for x in lcdarray:
            x.setSegmentStyle( QLCDNumber.Flat)



        layoutMain =  QtWidgets.QHBoxLayout(self.main_widget)
        layoutGraphs = QtWidgets.QVBoxLayout(self.main_widget)

        self.threadpool = QThreadPool()
        self.thread1 = QThread()
        self.thread1= movement(self.main_widget, width=6, height=5, dpi=100)
        # dc = movement(self.main_widget, width=6, height=5, dpi=100)
        self.thread2 = QThread()
        self.thread2 = distance(self.main_widget, width=6, height=5, dpi=100)
        # se=distance(self.main_widget, width=6, height=5, dpi=100)

        layoutGraphs.addWidget(self.thread1)
        layoutGraphs.addWidget(self.thread2)

        layoutresult = QtWidgets.QGridLayout(self.main_widget)

        layoutresult.addWidget(self.posx,0,0)
        layoutresult.addWidget(lcdx,0,1)
        layoutresult.addWidget(posy,1,0)
        layoutresult.addWidget(lcdy,1,1)
        layoutresult.addWidget(posdx,2,0)
        layoutresult.addWidget(lcddx,2,1)
        layoutresult.addWidget(posdy,3,0)
        layoutresult.addWidget(lcddy,3,1)
        layoutresult.addWidget(veldx,4,0)
        layoutresult.addWidget(lcdvdx,4,1)
        layoutresult.addWidget(veldy,5,0)
        layoutresult.addWidget(lcdvdy,5,1)
        layoutresult.addWidget(self.label,6,0)      
        layoutresult.addWidget(lcd5,6,1)
        layoutresult.addWidget(self.labelm10,7,0)
        layoutresult.addWidget(lcd10,7,1)
        layoutresult.addWidget(label1200,8,0)

        layoutMain.addLayout(layoutGraphs)
        layoutMain.addLayout(layoutresult)

        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)
        self.statusBar().showMessage("Program ", 2000)
    def fileQuit(self):
        self.close()
    def closeEvent(self, ce):
        self.fileQuit()
    def about(self):
        QtWidgets.QMessageBox.about(self, "About",
    """Program to control movement and velocity"""
    )
qApp = QtWidgets.QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("%s" % progname)
aw.show()
sys.exit(qApp.exec_())
#qApp.exec_()

0 个答案:

没有答案