首页 > 解决方案 > 使用 pyqt 将绘图添加到 GraphicsLayoutWidget

问题描述

我想将绘图添加到 GraphicsLayoutWidget。但是我尝试使用我编写的代码如下。

但现在我想改变我有两种类型的消息,一种是实时模式,另一种是录制模式。但是我想在实时模式下再添加一个绘图项目。

可以肯定的是,我还在代码中添加了一些注释以使您有所了解。我只粘贴了部分代码。

我已经在堆栈中进行了搜索,但找不到解决我问题的答案。

from pyqtgraph.Qt import QtCore, QtGui
import threading
import pyqtgraph as pg
import socket
import psutil
import time
import struct
import sys
import collections
import os
import PySimpleGUI as sg

import easygui




visualize_recorded_msg = 1
driver_called_from_outside = 0

BufferLength = 500
marker_size = 14

if 0 == visualize_recorded_msg:
    if 0 == driver_called_from_outside:
        driver_name = 'sss'
else:
    name_of_the_recorded_file = 'sss.bin'



########################################################################################################################
def get_pid_and_kill(process_name):
    for proc in psutil.process_iter():
        if proc.name() == process_name:
            p = psutil.Process(proc.pid)
            p.terminate()
            print("Process " + process_name + " terminated")


if 0 == visualize_recorded_msg:
    if 0 == driver_called_from_outside:
        from subprocess import Popen

        get_pid_and_kill(driver_name.split(("/"))[-1])
        get_pid_and_kill(driver_name.split(("\\"))[-1])
        get_pid_and_kill("cmd.exe")
        Popen([driver_name])
        print("The driver started")
        time.sleep(1)

    # TCP/IP Socket creation
    HOST = '145.0.0.10'
    PORT = 8085

    try:
        socket_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket_connection.settimeout(3)
        socket_connection.connect((HOST, PORT))
        socket_connection.settimeout(None)
        print("Socket successfully created")
    except socket.error as err:
        raise SystemExit("Socket creation failed with error %s" % err)
else:
    file_handle = open(name_of_the_recorded_file, 'rb')

    all_msgs = file_handle.read()
    file_handle.close()


def open_exit_button():
    even_name = 'kill the driver'
    layout = [[sg.Button(even_name, button_color=('white', 'springgreen4'))]]

    window = sg.Window('Configurations', layout)
    while True:  # Event Loop
        event, values = window.read(timeout=10)

        if event == sg.WIN_CLOSED or event == even_name:
            if 0 == visualize_recorded_msg:
                get_pid_and_kill(driver_name.split(("/"))[-1])
                get_pid_and_kill(driver_name.split(("\\"))[-1])
            os._exit(1)
            break

    window.close()


class Visualizer(object):

    def __init__(self):
        self.app = QtGui.QApplication(sys.argv)

        self.view = pg.GraphicsLayoutWidget()
        self.view.setWindowTitle('')

        self.w1 = self.view.addPlot(row=0, col=0, title='Accelerometer 1')
        self.w1.showGrid(x=True, y=True)
        self.w1.addLegend()
        self.w1.setLabel(axis='bottom', text='Time [s]')
        self.w1.setLabel(axis='left', text='')
        self.w1.curve2 = self.w1.plot(name='')
        self.w1.curve3 = self.w1.plot(name='')

        self.w2 = self.view.addPlot(row=1, col=0, title='')
        self.w2.showGrid(x=True, y=True)
        self.w2.addLegend()
        self.w2.setLabel(axis='bottom', text='Time [s]')
        self.w2.setLabel(axis='left', text='')
        self.w2.curve2 = self.w2.plot(name='')
        self.w2.curve3 = self.w2.plot(name='')

        self.w3 = self.view.addPlot(row=2, col=0, title='Average')
        self.w3.showGrid(x=True, y=True)
        self.w3.setLabel(axis='bottom', text='Time [s]')
        self.w3.setLabel(axis='left', text='')
        self.w3.curve1 = self.w3.plot()

        self.w4 = self.view.addPlot(row=3, col=0, title='result ')
        self.w4.showGrid(x=True, y=True)
        self.w4.setLabel(axis='bottom', text='Time [s]')
        self.w4.setLabel(axis='left', text='')
        self.w4.curve1 = self.w4.plot()

        self.a = collections.deque(maxlen=BufferLength)
        self.b = collections.deque(maxlen=BufferLength)
        self.c = collections.deque(maxlen=BufferLength)
        self.d = collections.deque(maxlen=BufferLength)
        self.e = collections.deque(maxlen=BufferLength)
        self.f = collections.deque(maxlen=BufferLength)

        self.view.show()

        self.prevFrameCnt = 0
        self.iteration_index = 0
        self.li_det = 0
        self.str_mot = 1

    @staticmethod
    def start():
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def message_parser(self, data):
        out1 = struct.unpack("<L", data[0:4])[0]
        out2 = data[4]
        out3 = data[5]
        out4 = data[6]
        out5 = struct.unpack("<h", data[7:9])[0]
        out6 = struct.unpack("<H", data[9:11])[0]
        out7 = struct.unpack("<H", data[11:13])[0] 
        out8 = struct.unpack("<H", data[17:19])[0] 
        out9 = struct.unpack("<H", data[19:21])[0] 

        return [out1, out2, out3, out4, out5, out6, out7, out8, out9]

    def update(self):

        if 0 == visualize_recorded_msg:
            # Receive TCP/IP packet
            try:
                data = socket_connection.recv(64)
            except socket.timeout as e:
                print(e)
                return
            except (ConnectionResetError, OSError):
                raise SystemExit("Remote server closed")

            # Decode TCP/IP packet
            output = self.message_parser(data)
        else:
            msg_length = 21 
            try:
                data = all_msgs[self.iteration_index: self.iteration_index + msg_length]
                decode_output = self.message_parser(data)
                self.iteration_index += msg_length
            except:
                print('End of file')
                

        x = decode_output[0]
        y = decode_output[4]
        z = decode_output[5]
        x1 = decode_output[6]
        y1 = decode_output[7]
        z1 = decode_output[8]


        if self.prevFrameCnt == x:
            MovDet = decode_output[1]
            LiDet = decode_output[2]
            MotDet = decode_output[3]

            self.a.append(y)
            self.c.append(z1)
            self.d.append(y1)

            self.w2.curve2.setData(self.c, pen=None, symbol='t', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(0, 114, 189))
            self.w2.curve3.setData(self.d, pen=None, symbol='t1', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))
            self.w3.curve1.setData(self.a, pen=None, symbol='d', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=('g'))
            self.w4.curve1.setData(self.f, pen=None, symbol='o', symbolPen=None,
                                   symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))

            if (1 == self.li_det) or (105 == LiDet):
                self.li_det = 1

        else:
            MovDet = decode_output[1]
            LiDet = decode_output[2]
            MotDet = decode_output[3]

            self.b.append(z1)
            self.d.append(y1)
            
            self.w1.curve2.setData(self.b, pen=None, symbol='t', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(0, 114, 189))
            self.w1.curve3.setData(self.d, pen=None, symbol='t1', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))
            self.prevFrameCnt = x



        self.view.show()

    def animation(self):
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(1)
        self.start()


def visualization():
    v = Visualizer()
    v.animation()


def main():
    if 0 == driver_called_from_outside:
        thread = threading.Thread(target=visualization)
        thread.start()
        open_exit_button()
    else:
        visualization()


if __name__ == '__main__':
    main()

标签: pythonpython-3.xpyqt5pyqtgraph

解决方案


推荐阅读