class TestWidget(pg.PlotWidget):
    def __init__(self):
        super().__init__()

        self._layout = GraphicsLayout()  # 创建一个网格布局
        self._layout.setContentsMargins(10, 10, 10, 10)
        self.setCentralItem(self._layout)

        label = pg.LabelItem()

        label.setText("这是一个label Item")
        label.item.setPos(100, 100)

        text = pg.TextItem()
        text.setText("这是一个text Item")

        plot_01 = pg.PlotItem()
        plot_01.addItem(label)
        plot_01.setMenuEnabled(False)
        plot_01.setClipToView(True)
        plot_01.hideAxis('left')  # 隐藏左纵坐标轴
        plot_01.hideAxis('bottom')

        plot_01.showAxis('right')  # 显示右纵坐标轴
        # 字体沿Y轴翻转
        plot_01.invertY()
        plot_01.setDownsampling(mode='peak')

        plot_01.setRange(xRange=(0, 1), yRange=(0, 1))

        axis_width = plot_01.getAxis("right").width()
        axis_height = plot_01.getAxis("bottom").height()
        axis_offset = QtCore.QPointF(axis_width, axis_height)
        bottom_view = plot_01.getViewBox()
        # bottom_right= bottom_view.mapSceneToView(
        # bottom_view.sceneBoundingRect().bottomRight() - axis_offset)
        # top_left = bottom_view.mapSceneToView(bottom_view.sceneBoundingRect().topLeft())
        # label.setPos(top_left)
        # plot_02 = pg.PlotItem()
        # plot_02.addItem(label)

        #
        self._layout.addItem(plot_01)
        self._layout.nextRow()
        self._layout.addItem(plot_01)
Beispiel #2
0
    def __init__(self, parent: QWidget):
        GraphicsView.__init__(self, parent)
        layout = GraphicsLayout()
        self.setCentralItem(layout)

        self._image_item = ImageItem()
        self.viewbox = ViewBox(layout, lockAspect=True, invertY=True)
        self.viewbox.addItem(self._image_item)
        layout.addItem(self.viewbox)

        self.scale = ScaleBar(size=10, suffix='μm')
        self.scale.setParentItem(self.viewbox)
        self.scale.anchor((1, 1), (1, 1), offset=(-20, -20))
        self.scale.hide()

        self._show_mask = False
        self.blend_mode = QPainter.CompositionMode_Screen
        self.items: List[ChannelImageItem] = None
Beispiel #3
0
class TilesView(GraphicsView):
    def __init__(self, parent: QWidget):
        GraphicsView.__init__(self, parent)

        self.layout = GraphicsLayout()
        self.setCentralItem(self.layout)

        self.tiles: Dict[str, TileView] = dict()

    def clear(self):
        self.layout.clear()
        self.tiles.clear()

    def get_cell(self, i: int):
        l = len(self.tiles.keys())
        if l > 9:
            rows = (0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
            cols = (0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3)
        elif l > 4:
            rows = (0, 0, 0, 1, 1, 1, 2, 2, 2)
            cols = (0, 1, 2, 0, 1, 2, 0, 1, 2)
        else:
            rows = (0, 0, 1, 1)
            cols = (0, 1, 0, 1)
        return rows[i], cols[i]

    def set_images(self, items: List[ChannelImageItem]):
        self.clear()
        if len(items) > 0:
            for item in items:
                tile = TileView(self.layout, item)
                self.tiles[item.channel.metal] = tile

            first_tile = self.tiles[list(self.tiles.keys())[0]]
            for i, tile in enumerate(self.tiles.values()):
                if first_tile is not tile:
                    tile.linkView(ViewBox.XAxis, first_tile)
                    tile.linkView(ViewBox.YAxis, first_tile)
                cell = self.get_cell(i)
                self.layout.addItem(tile, cell[0], cell[1])

    def fit_all_tiles(self):
        for name, tile in self.tiles.items():
            tile.autoRange()
Beispiel #4
0
class SystemEngine(object):
    def __init__(self, interType, ui):  #Construtor da classe
        self.ui = ui
        self.interType = interType

        self.timer = QtCore.QTimer()

        self.ser1 = SerialManager(interType)

        self.ySize = 500

        if self.interType == 0:
            self.x_scale = 10
            self.nCurves = 2
            self.y_min = [0, 0]
            self.y_max = [32700, 10000]
            self.xSize = 780

            self.color = ['r', 'g']
            self.name = ["Força", "Tensão no Calibrante"]
            self.unit = ["Tonf", "mV"]

        elif self.interType == 1:
            self.x_scale = 10
            self.nCurves = 3
            self.y_min = [0, 0, 0]
            self.y_max = [32700, 10000, 5000]

            self.color = ['r', 'g', 'y']
            self.name = ["Temperatura", "Força", "Potência"]
            self.unit = ["ºC", "N", "W"]
            self.xSize = 735

        self.ser1.startPort(str(self.ser1.portList[1].device), 115200)
        self.ser1.serialListPanel(self.ui)

        self.layout = GraphicsLayout()

        self.updateTimer()

        self.scene = QtGui.QGraphicsScene()

        self.scene.addItem(self.layout)
        self.updateScale()

        #self.layout.setMaximumSize(770,550)
        self.scene.focusItem()

        self.sceneSelector(self.scene)

        self.ui.menuPlay_Pause = QtWidgets.QAction(self.ui.MainWindow)
        self.ui.menuPlay_Pause.setText("Play")
        self.ui.menuPlay_Pause.setObjectName("menuPlay_Pause")

        self.ui.menuBar.addAction(self.ui.menuPlay_Pause)
        self.ui.menuPlay_Pause.setCheckable(True)

        self.ui.menuPlay_Pause.triggered.connect(self.playPauseButtonAnimation)

        self.ui.linkActions()

        self.ui.t_max.returnPressed.connect(self.updateScale)
        self.ui.f_max.returnPressed.connect(self.updateScale)
        self.ui.f_min.returnPressed.connect(self.updateScale)
        self.ui.p_max.returnPressed.connect(self.updateScale)
        self.ui.p_min.returnPressed.connect(self.updateScale)

        if self.interType == 1:
            self.ui.temp_max.returnPressed.connect(self.updateScale)
            self.ui.temp_min.returnPressed.connect(self.updateScale)

        self.ui.samplingCBox.currentIndexChanged.connect(self.updateTimer)
        self.timeant = time.time()
        self.timer.timeout.connect(self.updateData)

        thread_instance = QtCore.QThread()
        thread_instance.start()
        thread_instance.exec_()
        self.timer.start(100)

    def playPauseButtonAnimation(self):
        if (self.ui.menuPlay_Pause.text() == "Play"):
            self.ui.menuPlay_Pause.setText("Pause")
            self.ui.startTimeLabel.setText(self.ui.currentTimeLabel.text())
        else:
            self.ui.menuPlay_Pause.setText("Play")

    def sceneSelector(self, scene):
        scene.setSceneRect(0, 0, 1000, 600)
        self.ui.CentralGraph.setScene(scene)
        self.ui.CentralGraph.setSceneRect(scene.sceneRect())
        self.ui.CentralGraph.setBackgroundBrush(QtCore.Qt.black)
        self.ui.CentralGraph.setInteractive(False)

    def updateData(self):
        #print(time.time()-self.timeant)
        if (self.ui.menuPlay_Pause.isChecked() == True):
            readData = self.ser1.read()  # Lê o dado da serial
            readData = readData.decode('utf8')
            #print(readData)
            dado = readData.split(' ', self.nCurves + 1)

            dado[len(dado) - 1] = dado[len(dado) - 1].split('\n', 2)[0]
            try:
                if self.interType == 0:
                    self.ui.forceLabel.setText(str(dado[0]) + " Tonf")
                    self.ui.calibratorLabel.setText(
                        str(dado[1].split()[0]) + " mV")

                elif self.interType == 1:
                    self.ui.tempLabel.setText(str(dado[0]) + "ºC")
                    self.ui.forceLabel.setText(str(dado[1].split()[0]) + " kN")
                    self.ui.powLabel.setText(str(dado[2].split()[0]) + " kW")

            except IndexError:
                print("Erro no Indice do Array Enviado pela Serial")
            try:
                self.graph.updateGraph(dado)

            except IndexError:
                print("Erro: Array inválido")
                print(dado)

        else:
            pass
        self.timeant = time.time()

    def updateScale(self):
        try:
            self.x_scale = int(self.ui.t_max.text())

            if self.interType == 0:
                self.y_min[0] = int(self.ui.f_min.text())
                self.y_max[0] = int(self.ui.f_max.text())
                self.y_min[1] = int(self.ui.p_min.text())
                self.y_max[1] = int(self.ui.p_max.text())

            elif self.interType == 1:
                self.y_min[0] = int(self.ui.temp_min.text())
                self.y_max[0] = int(self.ui.temp_max.text())
                self.y_min[1] = int(self.ui.f_min.text())
                self.y_max[1] = int(self.ui.f_max.text())
                self.y_max[2] = int(self.ui.p_max.text())
                self.y_min[2] = int(self.ui.p_min.text())

        except ValueError:
            self.x_scale = 100
            self.y_min[0] = 0
            self.y_max[0] = 32700
            self.y_min[1] = 0
            self.y_max[1] = 10000

            if self.interType == 1:
                self.y_min[2] = 0
                self.y_max[2] = 5000

            print("Erro!: Campos de Escala Vazios")

        if (self.x_scale == "0"):
            self.x_scale = "1"

        self.layout.clear()
        self.layout.setMinimumSize(500, 600)
        self.layout.setMaximumSize(500, 600)
        self.graph = Graph(self.time[0] / 1000, self.x_scale, self.nCurves,
                           self.y_min, self.y_max, self.xSize, self.ySize,
                           self.color, self.name, self.unit)

        self.layout.addItem(self.graph.axis[0],
                            row=1,
                            col=1,
                            rowspan=1,
                            colspan=1)
        for n in range(1, self.nCurves):
            self.layout.addItem(self.graph.axis[n],
                                row=1,
                                col=n + 2,
                                rowspan=1,
                                colspan=1)

        self.layout.addItem(self.graph, row=1, col=2, rowspan=1, colspan=1)
        self.layout.addItem(self.graph.axisTime,
                            row=2,
                            col=2,
                            rowspan=1,
                            colspan=1)

        self.scene.focusItem()

    def updateTimer(self):
        self.time = self.ui.samplingCBox.currentText().split(" ")
        self.time[0] = int(self.time[0])
        #print(self.time[0])
        if (self.time[0] < 100):
            self.time[0] = 1000 * self.time[0]

        self.timer.stop()
        self.timer.start(self.time[0])
class DataWidget(QWidget):
    def __init__(self, parent, shared_data):
        super(DataWidget, self).__init__(parent)
        self.__shared_data = shared_data
        self.__shared_data.update_sync.emit()

        # Add the file selection controls
        self.__dir_picker_button = QPushButton()
        self.__dir_picker_button.setEnabled(True)
        self.__dir_picker_button.setText("Load data")
        self.__dir_picker_button.setIcon(self.style().standardIcon(QStyle.SP_DirIcon))
        self.__dir_picker_button.setToolTip('Select the directory using the file explorer')
        self.__dir_picker_button.clicked.connect(self.__open_dir_picker)

        # Add the sync controls
        self.__sync_time_label = QLabel()
        self.__sync_time_label.setText('Enter the timecode (HH:mm:ss:zzz) : ')

        self.__sync_time_edit = QTimeEdit()
        self.__sync_time_edit.setDisplayFormat('HH:mm:ss:zzz')
        self.__sync_time_edit.setEnabled(False)

        self.__sync_time_button = QPushButton()
        self.__sync_time_button.setText('Sync data')
        self.__sync_time_button.setEnabled(False)
        self.__sync_time_button.clicked.connect(self.__sync_data)

        # Create the layout for the file controls
        dir_layout = QHBoxLayout()
        dir_layout.setContentsMargins(0, 0, 0, 0)
        dir_layout.addWidget(self.__dir_picker_button)
        dir_layout.addStretch(1)
        dir_layout.addWidget(self.__sync_time_label)
        dir_layout.addWidget(self.__sync_time_edit)
        dir_layout.addWidget(self.__sync_time_button)

        # Create the axis and their viewbox
        self.__x_axis_item = AxisItem('left')
        self.__y_axis_item = AxisItem('left')
        self.__z_axis_item = AxisItem('left')

        self.__x_axis_viewbox = ViewBox()
        self.__y_axis_viewbox = ViewBox()
        self.__z_axis_viewbox = ViewBox()

        # Create the widget which will display the data
        self.__graphic_view = GraphicsView(background="#ecf0f1")
        self.__graphic_layout = GraphicsLayout()
        self.__graphic_view.setCentralWidget(self.__graphic_layout)

        # Add the axis to the widget
        self.__graphic_layout.addItem(self.__x_axis_item, row=2, col=3, rowspan=1, colspan=1)
        self.__graphic_layout.addItem(self.__y_axis_item, row=2, col=2, rowspan=1, colspan=1)
        self.__graphic_layout.addItem(self.__z_axis_item, row=2, col=1, rowspan=1, colspan=1)

        self.__plot_item = PlotItem()
        self.__plot_item_viewbox = self.__plot_item.vb
        self.__graphic_layout.addItem(self.__plot_item, row=2, col=4, rowspan=1, colspan=1)

        self.__graphic_layout.scene().addItem(self.__x_axis_viewbox)
        self.__graphic_layout.scene().addItem(self.__y_axis_viewbox)
        self.__graphic_layout.scene().addItem(self.__z_axis_viewbox)

        self.__x_axis_item.linkToView(self.__x_axis_viewbox)
        self.__y_axis_item.linkToView(self.__y_axis_viewbox)
        self.__z_axis_item.linkToView(self.__z_axis_viewbox)

        self.__x_axis_viewbox.setXLink(self.__plot_item_viewbox)
        self.__y_axis_viewbox.setXLink(self.__plot_item_viewbox)
        self.__z_axis_viewbox.setXLink(self.__plot_item_viewbox)

        self.__plot_item_viewbox.sigResized.connect(self.__update_views)
        self.__x_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)
        self.__y_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)
        self.__z_axis_viewbox.enableAutoRange(axis=ViewBox.XAxis, enable=True)

        # Create the final layout
        self.__v_box = QVBoxLayout()
        self.__v_box.addLayout(dir_layout)
        self.__v_box.addWidget(self.__graphic_view)

        self.setLayout(self.__v_box)

        self.__restore_state()

    def __open_dir_picker(self):
        self.__shared_data.data_file_path = QFileDialog.getOpenFileUrl(self, 'Open the Hexoskin data directory',
                                                                       QDir.homePath())[0]
        if self.__shared_data.data_file_path is not None:
            try:
                self.__load_data()
                self.__add_selector_acc_gyr()
                self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')
            except FileNotFoundError:
                pass
            except UnicodeDecodeError:
                pass

    def __load_data(self):
        if self.__shared_data.data_file_path is not None:
            self.__shared_data.import_parameter()

    def __show_data(self, field1, field2, field3):
        if self.__shared_data.parameter is not None:
            # Generate the timecodes if needed
            if len(self.__shared_data.parameter['TIMECODE']) == 0:
                if self.__shared_data.sampling_rate is None:
                    result = False
                    while not result and result == 0:
                        result = self.__show_sampling_rate_picker()

                self.__shared_data.add_timecode()

            self.__x_axis_viewbox.clear()
            self.__y_axis_viewbox.clear()
            self.__z_axis_viewbox.clear()

            # Show the 3 selected fields
            self.__x_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field1))),
                                                        pen='#34495e'))
            self.__y_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field2))),
                                                        pen='#9b59b6'))
            self.__z_axis_viewbox.addItem(PlotCurveItem(list(map(int, self.__shared_data.parameter.get(field3))),
                                                        pen='#3498db'))

            self.__x_axis_item.setLabel(field1, color="#34495e")
            self.__y_axis_item.setLabel(field2, color="#9b59b6")
            self.__z_axis_item.setLabel(field3, color="#3498db")

            # Add the middle line and the bottom timecodes
            timecodes = self.__shared_data.parameter['TIMECODE']
            middle = [0] * len(timecodes)
            self.__plot_item_viewbox.addItem(PlotCurveItem(middle, pen='#000000'))
            self.__plot_item.getAxis('bottom').setTicks(
                self.__generate_time_ticks(timecodes, self.__shared_data.sampling_rate))

            # Enable the controls
            self.__sync_time_edit.setEnabled(True)
            self.__sync_time_button.setEnabled(True)
            self.__dir_picker_button.setEnabled(False)
        self.__update_views()

    def __update_views(self):
        self.__x_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())
        self.__y_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())
        self.__z_axis_viewbox.setGeometry(self.__plot_item_viewbox.sceneBoundingRect())

    def __generate_time_ticks(self, timecodes, rate):
        ticks = list()

        steps = [rate * 30, rate * 15, rate * 5, rate]
        for step in steps:
            temp = list()
            i = step
            while i in range(len(timecodes)):
                temp.append((i, timecodes[i].strftime('%H:%M:%S:') + str(int(timecodes[i].microsecond / 1000))))
                i += step
            ticks.append(temp)

        return ticks

    def __sync_data(self):
        self.__shared_data.data_sync = self.__sync_time_edit.text()
        self.__shared_data.update_sync.emit()

    def __show_sampling_rate_picker(self) -> bool:
        self.__shared_data.sampling_rate, result = QInputDialog.getInt(self, 'Set sampling rate value', 'Sampling rate')
        return result

    def __add_selector_acc_gyr(self):
        if 'GYR_X' in self.__shared_data.parameter.keys() or 'GYR_Y' in self.__shared_data.parameter.keys() \
                or 'GYR_Z' in self.__shared_data.parameter.keys():
            show_acc = QPushButton()
            show_acc.setText('Show Accelerometer Axis')
            show_acc.clicked.connect(self.__show_acc)

            show_gyr = QPushButton()
            show_gyr.setText('Show Gyroscope Axis')
            show_gyr.clicked.connect(self.__show_gyr)

            layout = QHBoxLayout()
            layout.addWidget(show_acc)
            layout.addWidget(show_gyr)
            layout.addStretch(1)

            self.__v_box.addLayout(layout)

    def __show_acc(self):
        self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')

    def __show_gyr(self):
        self.__show_data('GYR_X', 'GYR_Y', 'GYR_Z')

    def __restore_state(self):
        if self.__shared_data.parameter is not None:
            self.__add_selector_acc_gyr()
            self.__show_data('ACC_X', 'ACC_Y', 'ACC_Z')
            print('trigger reimport')
        if self.__shared_data.data_sync is not None:
            text_time = self.__shared_data.data_sync.split(':')
            time = QTime()
            time.setHMS(int(text_time[0]), int(text_time[1]), int(text_time[2]), int(text_time[3]))
            self.__sync_time_edit.setTime(time)