Esempio n. 1
0
class VContainer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        # self.addWidgets(widgets)
        self.vcontainer = QVBoxLayout(self)
        self.vcontainer.setGeometry(QRect(0, 0, 10, 10))

    def addWidgets(self, widgets):
        for widget in widgets:
            self.vcontainer.addWidget(widget)
        self.vcontainer.addStretch(1)
        self.vcontainer.setSpacing(1)
Esempio n. 2
0
    def setGeometry(self, r):
        QVBoxLayout.setGeometry(self, r)
        try:
            wid = self.parentWidget().parentWidget()

            new_size = self.minimumSize()
            if new_size == self._last_size: return
            self._last_size = new_size

            twid = wid.titleBarWidget()
            if twid is not None:
                theight = twid.sizeHint().height()
            else:
                theight = 0

            new_size += QSize(0, theight)
            wid.setMinimumSize(new_size)

        except Exception:
            pass
    def __init__(self):
        print("start")
        QWidget.__init__(self)
        self.setMinimumSize(QSize(600, 500))
        self.setWindowTitle("Iron_BCI")
        pybutton1 = QPushButton('Main menu', self)
        pybutton1.clicked.connect(self.To_main_menu)
        pybutton1.resize(65, 50)
        pybutton1.move(250, 5)

        pybutton2 = QPushButton('Furie_start', self)
        pybutton2.clicked.connect(self.Furie_start)
        pybutton2.resize(65, 50)
        pybutton2.move(250, 55)

        self.figure = plt.figure(figsize=(0, 1), facecolor='b',
                                 edgecolor='r')  #  color only
        self.canvas = FigureCanvas(self.figure)
        self.figure.subplots_adjust(0.2, 0.4, 0.8, 1)  # only graph

        self.figure1 = plt.figure(figsize=(0, 1), facecolor='b')  #  color only
        self.canvas1 = FigureCanvas(self.figure1)
        self.figure1.subplots_adjust(0.2, 0.4, 0.8, 1)  # only graph

        layout = QVBoxLayout()
        layout.setContentsMargins(50, 100, 0, 11)  # move background
        layout.setGeometry(QRect(0, 0, 80, 68))  # nothing
        layout.addWidget(self.canvas)
        layout.addWidget(self.canvas1)

        le_num1 = QLineEdit(self)
        le_num1.setFixedSize(60, 20)  # size
        le_num1.move(10, 0)

        pb_num1 = QPushButton('HPS', self)
        pb_num1.setFixedSize(50, 60)  # size
        pb_num1.clicked.connect(self.show_dialog_num1)
        #layout.addWidget(self.le_num1)
        pb_num1.move(30, 0)

        self.setLayout(layout)
Esempio n. 4
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.start = '2164 8753'
        self.cnt = 8  # 当前九宫格已经填入的数字的个数
        self.solver = Solver(self.start, max_depth=20)
        self.updater = UpdateObj(self)
        self.myThread = QThread()
        self.updater.moveToThread(self.myThread)
        self.initUI()
        self.bindSlots()

    '''
    布置所有组件
    '''

    def initUI(self):
        with open('./res/style.qss', encoding='utf8', mode='r') as f:
            self.qss = f.read()
        self.setStyleSheet(self.qss)  # 应用qss样式表
        self.setWindowTitle('八数码实验')
        self.setWindowIcon(QIcon('./res/8puzzle.png'))  # 设置应用图标

        self.title = QLabel('八数码问题的实验程序', self)
        self.title.setObjectName('title')
        self.title.move(78, 52)
        self.setGeometry(300, 300, 800, 600)
        self.setFixedSize(800, 600)
        QLabel('最大搜索深度', self).setGeometry(260, 455, 95, 20)
        self.max_depth = QLineEdit(self)
        self.max_depth.setGeometry(QRect(350, 452, 50, 22))
        self.max_depth.setText(str(self.solver.max_depth))

        # 左侧按钮集
        self.lbtns = [
            QPushButton('深度优先搜索', self),
            QPushButton('宽度优先搜索', self),
            QPushButton('启发式搜索1', self),
            QPushButton('启发式搜索2', self),
            QPushButton('启发式搜索3', self),
            QPushButton('全部运行(F5)', self)
        ]
        # 右侧按钮集
        self.rbtns = [
            QPushButton('随机生成', self),
            QPushButton('手动输入', self),
            QPushButton('清空', self),
            QPushButton('退出', self),
            QPushButton('解法演示', self),
            QPushButton('别点', self)
        ]
        # 初始状态禁用
        self.rbtns[4].setEnabled(False)
        self.lbtns[5].setShortcut(QKeySequence("F5"))
        # 分别将两侧按钮集添加到两个垂直布局中
        self.ver_layout1 = QVBoxLayout()
        self.ver_layout2 = QVBoxLayout()
        for btn in self.lbtns:
            self.ver_layout1.addWidget(btn)
        for btn in self.rbtns:
            self.ver_layout2.addWidget(btn)
        # 调整按钮栏的位置
        self.ver_layout1.setGeometry(QRect(87, 135, 140, 320))
        self.ver_layout2.setGeometry(QRect(572, 135, 140, 320))

        # 八数码的牌子设置为初始状态
        self.nums = [MyLabel(self) for _ in range(9)]
        for i, ch in enumerate(self.start):
            self.nums[i].setText(ch)
            self.nums[i].setEnabled(False)
        # 八数码棋盘
        self.puzzles = QFrame(self)
        self.puzzles.setObjectName('puzzles')
        self.puzzles.setGeometry(QRect(310, 135, 210, 210))
        # 设置八数码的九宫格显示
        grid = QGridLayout(self.puzzles)
        positions = [(i, j) for i in range(3) for j in range(3)]
        for label, position in zip(self.nums, positions):
            grid.addWidget(label, *position)
        # 构建结果表格
        self.result = QTableWidget(2, 6, self)
        self.result.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)  # 设置自适应列宽
        self.result.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.result.setHorizontalHeaderLabels(
            ['方法', '深度优先', '宽度优先', 'h1(n)', 'h2(n)', 'h3(n)'])
        for i in range(2):
            for j in range(6):
                self.result.setItem(i, j, QTableWidgetItem())  # 添加item
                self.result.item(i, j).setTextAlignment(
                    Qt.AlignCenter | Qt.AlignVCenter)  # 设置文本居中
        self.result.item(0, 0).setText('扩展节点数')
        self.result.item(1, 0).setText('生成节点数')
        self.result.setGeometry(QRect(87, 478, 630, 100))  # 调整表格位置
        # 设置logo
        self.logo = QLabel(self)
        self.logo.setGeometry(QRect(600, 10, 90, 100))
        jpg = QPixmap('./res/scnulogo.png').scaled(self.logo.width(),
                                                   self.logo.height())
        self.logo.setPixmap(jpg)
        # 增添提示
        self.descrip = QLabel(self)
        self.descrip.setGeometry(QRect(260, 360, 300, 100))
        self.descrip.setText(
            '''最大搜索深度过大可能会导致搜索时间过长\n(特别是BFS),导致程序无响应,需要强制关闭\nh1(n) =W(n) “不在位”的将牌数\nh2(n) = P(n)将牌“不在位”的距离和\nh3(n) = h(n)=P(n)+3S(n)'''
        )
        self.show()

    '''
    给必要的控件绑定槽函数
    '''

    def bindSlots(self):
        self.lbtns[0].clicked.connect(self.run_dfs)
        self.lbtns[1].clicked.connect(self.run_bfs)
        self.lbtns[2].clicked.connect(self.run_h1)
        self.lbtns[3].clicked.connect(self.run_h2)
        self.lbtns[4].clicked.connect(self.run_h3)
        self.lbtns[5].clicked.connect(self.run_all)
        self.rbtns[0].clicked.connect(self.random_state)
        self.rbtns[1].clicked.connect(self.manual_input)
        self.rbtns[2].clicked.connect(self.clear)
        self.rbtns[3].clicked.connect(self.close)
        self.rbtns[4].clicked.connect(self.updater.show_ans)
        self.rbtns[5].clicked.connect(self.useless)
        self.max_depth.textChanged[str].connect(self.change_max_depth)
        self.myThread.start()
        for w in self.nums:
            w.clicked.connect(w.input_num)

    '''
    用来皮一下的函数
    '''

    def useless(self):
        for _ in range(20):
            QMessageBox.about(self, '叫你别点', '欢迎大家学习人工智能导论')

    '''
    根据val更改最大搜索深度
    '''

    def change_max_depth(self, val):
        if re.search('^\\d+$', val):
            self.solver.max_depth = int(val)

    '''
    运行深度优先搜索算法,调用了Solver类的dfs方法,更新结果表格
    '''

    def run_dfs(self):
        res, gen, expand = self.solver.dfs()
        self.rbtns[4].setEnabled(True if res else False)  # 是否允许进行解法演示
        print(res, gen, expand)
        self.result.item(0, 1).setText(str(expand))
        self.result.item(1, 1).setText(str(gen))

    '''
    运行宽度优先搜索算法,调用了Solver类的bfs算法,更新结果表格
    '''

    def run_bfs(self):
        res, gen, expand = self.solver.bfs()
        self.rbtns[4].setEnabled(True if res else False)  # 是否允许进行解法演示
        print(res, gen, expand)
        self.result.item(0, 2).setText(str(expand))
        self.result.item(1, 2).setText(str(gen))

    '''
    运行h1启发式搜索算法,调用了Solver类的hs1方法,更新结果表格
    '''

    def run_h1(self):
        res, gen, expand = self.solver.hs1()
        self.rbtns[4].setEnabled(True if res else False)  # 是否允许进行解法演示
        print(res, gen, expand)
        self.result.item(0, 3).setText(str(expand))
        self.result.item(1, 3).setText(str(gen))

    '''
    运行h2启发式搜索算法,调用了Solver类的hs2方法,更新结果表格
    '''

    def run_h2(self):
        res, gen, expand = self.solver.hs2()
        self.rbtns[4].setEnabled(True if res else False)  # 是否允许进行解法演示
        print(res, gen, expand)
        self.result.item(0, 4).setText(str(expand))
        self.result.item(1, 4).setText(str(gen))

    '''
    运行h3启发式搜索算法,调用了Solver类的hs1方法,更新结果表格
    '''

    def run_h3(self):
        res, gen, expand = self.solver.hs3()
        self.rbtns[4].setEnabled(True if res else False)  # 是否允许进行解法演示
        print(res, gen, expand)
        self.result.item(0, 5).setText(str(expand))
        self.result.item(1, 5).setText(str(gen))

    '''
    运行所有搜索算法,更新结果表格
    '''

    def run_all(self):
        self.run_dfs()
        self.run_bfs()
        self.run_h1()
        self.run_h2()
        self.run_h3()

    '''
    清空结果表
    '''

    def clear(self):
        for i in range(2):
            for j in range(1, 6):
                self.result.item(i, j).setText('')

    '''
    手动输入初始状态
    '''

    def manual_input(self):
        self.clear()  # 清空表格
        # 清空九宫格的数字,并设置为可点击,即允许输入
        for w in self.nums:
            w.setText('')
            w.setEnabled(True)
        # 未输入完成前不允许执行搜索和解法演示
        for b in self.lbtns:
            b.setEnabled(False)
        self.rbtns[4].setEnabled(False)
        # 计数器清零
        self.cnt = 0

    ''' 
    生成随机状态
    '''

    def random_state(self):
        self.start = ''.join([str(i) for i in random.sample(range(0, 9), 9)
                              ]).replace('0', ' ')
        self.solver.start = self.start
        # 更新ui
        for i, w in enumerate(self.nums):
            w.setText(self.start[i])
        self.rbtns[4].setEnabled(False)
    def __init__(self):
        print ("start")       
        QWidget.__init__(self)

        self.setMinimumSize(QSize(600, 500))    
        self.setWindowTitle("Iron_BCI") 
              

        self.figure = plt.figure(figsize=(0,2,),facecolor='y',  edgecolor='r') #  color only     
        self.figure1 = plt.figure(figsize=(0,2),facecolor='y') # color only
        self.figure2 = plt.figure(figsize=(0,2),facecolor='y')
        self.figure3 = plt.figure(figsize=(0,2),facecolor='y')
                
        self.canvas = FigureCanvas(self.figure)
        self.figure.subplots_adjust(0.2, 0.4, 0.8, 1)  # only graph 
        self.canvas1 = FigureCanvas(self.figure1)
        self.figure1.subplots_adjust(0.2, 0.4, 0.8, 1)  # only graph 
        self.canvas2 = FigureCanvas(self.figure2)
        self.figure2.subplots_adjust(0.2, 0.4, 0.8, 1)
        self.canvas3 = FigureCanvas(self.figure3)
        self.figure3.subplots_adjust(0.2, 0.4, 0.8, 1)
       # self.toolbar = NavigationToolbar(self.canvas, self)
       # self.toolbar1 = NavigationToolbar(self.canvas1, self)
        
        pybutton = QPushButton('graph', self)

        
        global axis_x
        axis_x=0

        pybutton.clicked.connect(self.clickMethod)
        pybutton.move(350, 10)
        pybutton.resize(100,32)
        
        layout = QVBoxLayout()
        layout.setContentsMargins(50,100,0,11) # move background
        layout.setGeometry(QRect(0, 0, 80, 68))# nothing  
      # layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)    
      # layout.addWidget(self.toolbar1)
        layout.addWidget(self.canvas1)        
        layout.addWidget(self.canvas2)  # background
        layout.addWidget(self.canvas3)
       # input dataufoff value  
        self.le_num1 = QLineEdit()
        self.le_num1.setFixedSize(50, 20) # size                        
        self.pb_num1 = QPushButton('HPS')
        self.pb_num1.setFixedSize(50, 60) # size
        self.pb_num1.clicked.connect(self.show_dialog_num1)
        layout.addWidget(self.le_num1)       
        self.pb_num1.move(10, 0)        
        layout.addWidget(self.pb_num1)
        self.setLayout(layout)
        # stop input data
        # start input data fps
        self.le_num2 = QLineEdit()
        self.le_num2.setFixedSize(50, 20) # size                        
        self.pb_num2 = QPushButton('fs')
        self.pb_num2.setFixedSize(50, 60) # size
        self.pb_num2.clicked.connect(self.show_dialog_num2)
        layout.addWidget(self.le_num2)       
        self.pb_num1.move(90, 100)        
        layout.addWidget(self.pb_num2)
        self.setLayout(layout)
        # stop input data fps
        # start input data low filter
        self.le_num3 = QLineEdit()
        self.le_num3.setFixedSize(50, 20) # size                        
        self.pb_num3 = QPushButton('LPF')
        self.pb_num3.setFixedSize(50, 60) # size
        self.pb_num3.clicked.connect(self.show_dialog_num3)     
        layout.addWidget(self.le_num3)       
        self.pb_num1.move(190, 100)        
        layout.addWidget(self.pb_num3)
        self.setLayout(layout)
Esempio n. 6
0
class App(QMainWindow):

    # create the default instance
    # noinspection PyArgumentList
    def __init__(self):
        super().__init__()

        # GUI default values
        self.title = "GPS Robot-Inferno"
        self.left = 10
        self.top = 100
        self.width = 1300
        self.height = 800

        # create the grid
        self.grid_width = 2.5
        self.grid_height = 3.5
        self.grid_x = 20
        self.grid_y = 28
        self.offset_x = 0
        self.offset_y = 0
        self.border_thickness = 1
        self.use_diagonals = True
        self.grid = Grid(self.grid_width, self.grid_height, self.grid_x,
                         self.grid_y, self.offset_x, self.offset_y,
                         self.border_thickness, self.use_diagonals)

        # create the important point variables
        self.rover_position = self.grid.get_node(0, 0)
        self.rover_actual_position = Vector()
        self.destinations = []
        self.home = self.grid.get_node(1, 1)
        self.current_path = []
        self.simple_path = []
        self.in_motion = False
        self.mode = AUTO
        self.rover_status = 0

        # setup client and signals
        self.send_queue = Queue()
        self.client = Client(self.send_queue)
        self.client.on_rover_position_changed.connect(self.rover_pos_changed)
        self.client.on_rover_actual_position_changed.connect(
            self.on_actual_position_updated)
        self.client.on_destination_reached.connect(self.on_point_reached)
        self.client.on_destination_update.connect(self.on_destinations_updated)
        self.client.on_rover_status_changed.connect(
            self.on_rover_status_update)
        self.client.on_node_changed.connect(self.on_node_changed)
        self.client.on_simple_path_changed.connect(self.on_simple_path_changed)
        self.client.on_path_changed.connect(self.on_path_changed)
        self.client.on_camera_button_pressed.connect(
            self.on_cam_on_off_clicked)
        self.client.on_go_home_pressed.connect(self.on_go_home_clicked)
        self.client.on_auto_switch.connect(self.on_autodrive_clicked)

        self.remote_on = False

        # create the actual GUI
        self.init_ui()

        # start the video stream
        self.stream = VideoStream()
        self.stream.changePixmap.connect(self.set_image)

    # actually builds the GUI
    # noinspection PyArgumentList
    def init_ui(self):

        # base effects
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.set_color(Qt.white)

        # layouts
        self.grid_panel = GridPanel(self, self.grid)
        self.button_panel = QVBoxLayout()
        self.mouse_layout = QGroupBox(self)
        self.simulate_panel = QGroupBox(self)
        self.rover_status_panel = QGroupBox(self)
        self.legend = QGroupBox(self)

        # set up legend
        self.legend.setTitle("Legend")
        grid_l = QGridLayout()
        color = QLabel()
        color.setText("<b>Color</b>")
        grid_l.addWidget(color, 0, 0)
        map_meaning = QLabel()
        map_meaning.setText("<b>Map Meaning</b>")
        grid_l.addWidget(map_meaning, 0, 1)
        meaning_rover = QLabel()
        meaning_rover.setText("<b>Rover Behavior</b>")
        grid_l.addWidget(meaning_rover, 0, 2)

        # rover - auto
        rover_auto = LegendButton(self, ROVER_AUTO)
        grid_l.addWidget(rover_auto, 1, 0)
        rover_auto_meaning = QLabel()
        grid_l.addWidget(rover_auto_meaning, 1, 1)
        rover_auto_meaning.setText("The rover is currently\n in autodrive")
        rover_auto_meaning_behavior = QLabel()
        rover_auto_meaning_behavior.setText("The rover is \ncurrently idle")
        grid_l.addWidget(rover_auto_meaning_behavior, 1, 2)

        # rover - manual
        rover_manual = LegendButton(self, ROVER_MAN)
        grid_l.addWidget(rover_manual, 2, 0)
        rover_manual_meaning = QLabel()
        grid_l.addWidget(rover_manual_meaning, 2, 1)
        rover_manual_meaning.setText("The rover is currently\n in manual")
        rover_manual_meaning_behavior = QLabel()
        rover_manual_meaning_behavior.setText(
            "The user turned\n the lights on")
        grid_l.addWidget(rover_manual_meaning_behavior, 2, 2)

        # rover - simulation
        rover_sim = LegendButton(self, ROVER_SIM)
        grid_l.addWidget(rover_sim, 3, 0)
        rover_sim_meaning = QLabel()
        grid_l.addWidget(rover_sim_meaning, 3, 1)
        rover_sim_meaning.setText("The rover is in\n simulation mode")
        rover_sim_meaning_behavior = QLabel()
        rover_sim_meaning_behavior.setText(
            "The rover has\"lost\" \nnetwork connection.")
        grid_l.addWidget(rover_sim_meaning_behavior, 3, 2)

        # Obstacle
        obstacle = LegendButton(self, OBSTACLE)
        grid_l.addWidget(obstacle, 4, 0)
        obstacle_meaning = QLabel()
        grid_l.addWidget(obstacle_meaning, 4, 1)
        obstacle_meaning.setText("An obstacle")

        # Border
        border = LegendButton(self, BORDER_SPACE)
        grid_l.addWidget(border, 5, 0)
        border_meaning = QLabel()
        grid_l.addWidget(border_meaning, 5, 1)
        border_meaning.setText(
            "An open area\n that borders an obstacle \nprovide space to navigate."
        )

        # Destination
        destination = LegendButton(self, DESTINATION)
        grid_l.addWidget(destination, 6, 0)
        destination_meaning = QLabel()
        grid_l.addWidget(destination_meaning, 6, 1)
        destination_meaning.setText("A destination")
        destination_meaning_behavior = QLabel()
        destination_meaning_behavior.setText(
            "The rover is moving\n to a destination")
        grid_l.addWidget(destination_meaning_behavior, 6, 2)

        # Queued Destination
        destination_f = LegendButton(self, FUTURE_DESTINATION)
        grid_l.addWidget(destination_f, 7, 0)
        destination_f_meaning = QLabel()
        grid_l.addWidget(destination_f_meaning, 7, 1)
        destination_f_meaning.setText("A queued festination")

        # home
        home = LegendButton(self, HOME)
        grid_l.addWidget(home, 8, 0)
        home_meaning = QLabel()
        grid_l.addWidget(home_meaning, 8, 1)
        home_meaning.setText("The rover's home")
        home_meaning_behavior = QLabel()
        home_meaning_behavior.setText("The rover is moving\n home")
        grid_l.addWidget(home_meaning_behavior, 8, 2)

        # path
        path = LegendButton(self, PATH)
        grid_l.addWidget(path, 9, 0)
        path_meaning = QLabel()
        grid_l.addWidget(path_meaning, 9, 1)
        path_meaning.setText("The rover's path")

        # simple_path
        simple_path = LegendButton(self, SIMPLE_PATH)
        grid_l.addWidget(simple_path, 10, 0)
        simple_path_meaning = QLabel()
        grid_l.addWidget(simple_path_meaning, 10, 1)
        simple_path_meaning.setText("The optimized points\n on the path")

        self.legend.setLayout(grid_l)
        self.legend.setFixedSize(300, 350)
        self.legend.move(990, 250)

        # set up rover status panel
        self.rover_status_panel.setTitle("Robot Status")
        grid_r = QVBoxLayout(self.rover_status_panel)
        self.rover_pos_label = QLabel()
        self.rover_pos_label.setText("Rover Coordinates: ")
        self.rover_coord_label = QLabel()
        self.rover_coord_label.setText("Map Position: ")
        self.rover_status_label = QLabel()
        self.rover_status_label.setText("Mode: ")
        grid_r.addWidget(self.rover_pos_label)
        grid_r.addWidget(self.rover_coord_label)
        grid_r.addWidget(self.rover_status_label)
        self.rover_status_panel.setFixedSize(300, 100)
        self.rover_status_panel.move(990, 150)

        # set up for simulation modes
        self.simulate_panel.setTitle("Simulation Mode")
        self.simulate_panel.setFixedSize(300, 125)
        self.simulate_panel.move(990, 15)

        # layout for simulation
        grid_s = QGridLayout(self.simulate_panel)

        # wait
        self.sim_wait_button = QRadioButton(self)
        self.sim_wait_button.setText("Wait")
        self.sim_wait_button.setChecked(True)
        self.sim_wait_button.toggled.connect(
            lambda: sim_state(self.sim_wait_button))

        # Go back
        self.sim_back_button = QRadioButton(self)
        self.sim_back_button.setText("Go To Previous Points")
        self.sim_back_button.toggled.connect(
            lambda: sim_state(self.sim_back_button))

        # Continue
        self.sim_cont_button = QRadioButton(self)
        self.sim_cont_button.setText("Continue With Waypoints")
        self.sim_cont_button.toggled.connect(
            lambda: sim_state(self.sim_cont_button))

        # Continue
        self.sim_home_button = QRadioButton(self)
        self.sim_home_button.setText("Go Home")
        self.sim_home_button.toggled.connect(
            lambda: sim_state(self.sim_home_button))

        # simulate network disconnect button
        self.sim_button = QPushButton(self)
        self.sim_button.setText("Start Simulation")
        self.sim_button.clicked.connect(self.on_sim_start)

        # add simulation buttons to layout
        grid_s.setSpacing(10)
        grid_s.addWidget(self.sim_wait_button, 0, 0)
        grid_s.addWidget(self.sim_back_button, 0, 1)
        grid_s.addWidget(self.sim_cont_button, 1, 0)
        grid_s.addWidget(self.sim_home_button, 1, 1)
        grid_s.addWidget(self.sim_button, 2, 0)
        self.simulate_panel.setEnabled(False)

        # set up for mouse actions
        self.mouse_layout.setTitle("On Click")
        self.mouse_layout.resize(350, 100)
        self.mouse_layout.setFixedSize(350, 100)

        # layout for mouse actions
        gridl = QGridLayout(self.mouse_layout)

        # add obstacle
        self.add_obstacle_button = QRadioButton(self)
        self.add_obstacle_button.setText("Add Obstacle")
        self.add_obstacle_button.setChecked(True)
        self.add_obstacle_button.toggled.connect(
            lambda: btnstate(self.add_obstacle_button))

        # remove obstacle
        self.remove_obstacle_button = QRadioButton(self)
        self.remove_obstacle_button.setText("Remove Obstacle")
        self.remove_obstacle_button.toggled.connect(
            lambda: btnstate(self.remove_obstacle_button))

        # add destination
        self.add_destination_button = QRadioButton(self)
        self.add_destination_button.setText("Add Destination")
        self.add_destination_button.toggled.connect(
            lambda: btnstate(self.add_destination_button))

        # remove destination
        self.add_home_button = QRadioButton(self)
        self.add_home_button.setText("Create/Move Home")
        self.add_home_button.toggled.connect(
            lambda: btnstate(self.add_home_button))

        # configure mouse action layout
        gridl.setSpacing(10)
        gridl.addWidget(self.add_obstacle_button, 0, 0)
        gridl.addWidget(self.remove_obstacle_button, 0, 1)
        gridl.addWidget(self.add_destination_button, 1, 0)
        gridl.addWidget(self.add_home_button, 1, 1)
        self.mouse_layout.setLayout(gridl)
        self.mouse_layout.setEnabled(False)
        self.button_panel.addWidget(self.mouse_layout)

        # clear destination button
        self.clear_destination_button = QPushButton(self)
        self.clear_destination_button.setText("Clear Destinations")
        self.clear_destination_button.clicked.connect(
            self.on_clear_destination_clicked)
        self.button_panel.addWidget(self.clear_destination_button)
        self.clear_destination_button.setEnabled(False)

        # clear obstacles
        self.clear_obstacles_button = QPushButton(self)
        self.clear_obstacles_button.setText("Clear All Obstacles")
        self.clear_obstacles_button.clicked.connect(self.on_clear_obstacles)
        self.button_panel.addWidget(self.clear_obstacles_button)
        self.clear_obstacles_button.setEnabled(False)

        # save and load buttons
        # self.save_button = QPushButton(self)
        # self.load_button = QPushButton(self)
        # self.save_button.setText("Save")
        # self.save_button.clicked.connect(self.save)
        # self.load_button.setText("Load")
        # self.load_button.clicked.connect(self.load)
        # self.save_load_layout = QHBoxLayout()
        # self.save_load_layout.addWidget(self.save_button)
        # self.save_load_layout.addWidget(self.load_button)
        # self.button_panel.addLayout(self.save_load_layout)

        # connect button
        self.connect_button = QPushButton(self)
        self.connect_button.setText("Connect")
        self.connect_button.clicked.connect(self.on_connect)
        self.button_panel.addWidget(self.connect_button)

        # turn cam on/off button
        self.cam_on_button = QPushButton(self)
        self.cam_on_button.setText("Turn Video Off")
        self.cam_on_button.clicked.connect(self.on_cam_on_off_clicked)
        self.button_panel.addWidget(self.cam_on_button)
        self.cam_on_button.setEnabled(False)

        # autodrive Button
        self.autodrive_button = QPushButton(self)
        self.autodrive_button.setText("Switch To Manual")
        self.autodrive_button.clicked.connect(self.on_autodrive_clicked)
        self.button_panel.addWidget(self.autodrive_button)
        self.autodrive_button.setEnabled(False)

        # go home Button
        self.go_home_button = QPushButton(self)
        self.go_home_button.setText("Go Home")
        self.go_home_button.clicked.connect(self.on_go_home_clicked)
        self.button_panel.addWidget(self.go_home_button)
        self.go_home_button.setEnabled(False)

        # Start/Stop Button
        self.start_stop_button = QPushButton(self)
        self.start_stop_button.setText("Start")
        self.start_stop_button.clicked.connect(self.on_start_stop_clicked)
        self.button_panel.addWidget(self.start_stop_button)
        self.start_stop_button.setEnabled(False)

        # create camera stream
        self.video_layout = QGroupBox(self)
        self.video_layout.setTitle("Video Stream")
        temp = QGridLayout(self.video_layout)
        self.video = QLabel(self)
        temp.addWidget(self.video)
        temp.setSpacing(0)
        self.video_layout.setLayout(temp)
        self.video_layout.setFixedSize(440, 320)
        self.video.resize(480, 320)
        self.button_panel.addWidget(self.video_layout)
        self.video_layout.setAlignment(Qt.AlignVCenter)

        # move panel to position!
        self.button_panel.setGeometry(QRect(525, 5, 440, 700))

    def on_connect(self):
        try:
            self.client.connect_to_server()
            self.stream.connect_to_server()
        except Exception as e:
            print(e)
        finally:
            self.client.start()
            self.stream.start()
            self.mouse_layout.setEnabled(True)
            self.clear_destination_button.setEnabled(True)
            self.clear_obstacles_button.setEnabled(True)
            self.cam_on_button.setEnabled(True)
            self.autodrive_button.setEnabled(True)
            self.start_stop_button.setEnabled(True)
            self.go_home_button.setEnabled(True)
            self.simulate_panel.setEnabled(True)

    # when the window closes
    def closeEvent(self, event):
        print("program closing")

        # close the client
        self.send_queue.put("Q")
        self.client.can_run = False
        self.stream.can_run = False
        time.sleep(1)
        self.client.quit()
        self.client.quit()

    # allows us to change the window color
    def set_color(self, color):
        p = self.palette()
        p.setColor(self.backgroundRole(), color)
        self.setPalette(p)

    # get the mouse mode
    def get_mouse_mode(self):
        return self.MOUSE_MODE

    def on_sim_start(self):
        try:
            if self.sim_button.text() == "Start Simulation":
                self.send_queue.put("SIM " + str(SIM_MODE))
                self.send_queue.put("MODE 1")
                self.sim_button.setText("Stop Simulation")
                self.start_stop_button.hide()
                self.autodrive_button.hide()
                self.video.hide()
                self.go_home_button.hide()
                self.mode = SIM
            else:

                self.sim_button.setText("Start Simulation")
                self.autodrive_button.show()
                self.video.show()
                self.go_home_button.show()
                print(self.client.remote_on)
                print(self.in_motion)
                if not self.client.remote_on:
                    self.send_queue.put("MODE 0")
                    self.start_stop_button.show()
                    self.mode = AUTO
                    #if self.in_motion:
                    #self.send_queue.put("GO")
                    #self.start_stop_button.setText("Stop")
                    #else:
                    #self.send_queue.put("S")
                else:
                    self.send_queue.put("S")
                    self.mode = MANUAL
                    self.send_queue.put("MODE 2")
            self.grid_panel.redraw_grid()
        except:
            print(traceback.format_exc())

    # when all the obstacles need to be cleared
    def on_clear_obstacles(self):
        temp = list(self.grid.all_obstacles)
        while len(temp) > 0:
            self.on_obstacle_removed(temp.pop(0))
        self.grid_panel.redraw_grid()

    # noinspection PyArgumentList
    @pyqtSlot(QImage)
    def set_image(self, image):
        self.video.setPixmap(QPixmap.fromImage(image))

    # updates the simple path
    # noinspection PyArgumentList
    @pyqtSlot(list)
    def on_simple_path_changed(self, path):
        temp = []
        for p in path:
            temp.append(self.grid.get_node(p.x, p.y))
        self.simple_path = temp
        self.grid_panel.redraw_grid()

    # updates the path
    # noinspection PyArgumentList
    @pyqtSlot(list)
    def on_path_changed(self, path):
        temp = []
        for p in path:
            temp.append(self.grid.get_node(p.x, p.y))
        self.current_path = temp
        self.grid_panel.redraw_grid()

    # when a node changes
    # noinspection PyArgumentList
    @pyqtSlot(Vector, int)
    def on_node_changed(self, node, node_type):
        try:
            self.grid.set_node(node.x, node.y, node_type)
            print(node.x, node.y, node_type)
            self.grid_panel.redraw_grid()
            if node_type == 1:
                self.validate_destinations(self.grid.get_node(node.x, node.y))
        except:
            print(traceback.format_exc())

    # when the destinations have changed server side
    # noinspection PyArgumentList
    @pyqtSlot(list)
    def on_destinations_updated(self, positions):
        try:
            if len(self.destinations) > 0:
                for d in self.destinations:
                    self.remove_destination(d)

            self.destinations = []
            for pos in positions:
                self.on_destination_added(self.grid.get_node(pos.x, pos.y))
            self.grid_panel.redraw_grid()
        except:
            print(traceback.format_exc())

    # noinspection PyArgumentList
    @pyqtSlot(Vector)
    def on_actual_position_updated(self, position):
        self.rover_actual_position = position
        self.rover_pos_label.setText("Rover Coordinates: " + str(position))

    # noinspection PyArgumentList
    @pyqtSlot(int)
    def on_rover_status_update(self, status):
        self.rover_status = status
        if status == 0:
            temp = "Idle"
        elif status == 1:
            temp = "Traveling to point"
        else:
            temp = "Going Home"

        self.rover_status_label.setText("Mode: " + temp)

    # factory for button click events.
    def on_click_event(self, vector):
        grid = self.grid

        # creates a click event for each button on the grid.
        def click_event():
            x = vector.x
            y = vector.y
            node = grid.nodes[x][y]
            something_happened = False
            print("My name is " + node.gridPos.x.__str__() + " " +
                  node.gridPos.y.__str__())
            print("My node Type is: " + node.node_type.__str__())
            print(int(MOUSE_MODE).__str__())

            # use the proper mouse event based on the obstacle
            if MOUSE_MODE == ADD_OBSTACLE:
                something_happened = self.on_obstacle_added(node)
            elif MOUSE_MODE == REMOVE_OBSTACLE:
                something_happened = self.on_obstacle_removed(node)
            elif MOUSE_MODE == ADD_DESTINATION:
                something_happened = self.on_destination_added(node)
            elif MOUSE_MODE == ADD_HOME:
                something_happened = self.on_home_added(node)

            # if there was a change in the grid, redraw it.
            if something_happened:
                self.grid_panel.redraw_grid()

        return click_event

    # if an obstacle is added to the grid we need to ensure pathfinding and drawing aren't distrupted.
    def on_obstacle_added(self, node):

        # if we have a valid node to work with.
        if node.node_type != 1 and node != self.rover_position:

            # we need to spread the grid.
            self.grid.set_node_type(node, 1)
            self.validate_destinations(node)
            return True
        return False

    def validate_destinations(self, node):
        try:

            border = self.grid.all_borders
            # IF there is a destination in play and it is hit by the border, it needs to be cleared.
            if len(self.destinations) > 0:
                if border.__contains__(
                        self.destinations[0]) or node == self.destinations[0]:
                    self.destinations.pop(0)

                    if len(self.destinations) > 0:
                        self.send_queue.put(
                            "D " + str(self.destinations[0].gridPos.x) + " " +
                            str(self.destinations[0].gridPos.y))
                    else:
                        self.current_path = []
                        self.simple_path = []
                        self.send_queue.put("D -1 -1")

                    self.send_queue.put("N " + str(node.gridPos.x) + " " +
                                        str(node.gridPos.y) + " " + str(1))
        except:
            print(traceback.format_exc())

    # if an obstacle was removed from the map we need to recalculate our path and borders.
    def on_obstacle_removed(self, node):
        if node.node_type == 1:
            self.grid.set_node_type(node, 0)
            self.send_queue.put("N " + str(node.gridPos.x) + " " +
                                str(node.gridPos.y) + " " + str(0))
            return True
        return False

    # if a destination was placed somewhere on the map
    def on_destination_added(self, node):
        print("adding destination")
        if node.node_type == 0 and node != self.rover_position and not self.destinations.__contains__(
                node):
            self.destinations.append(node)
            self.send_queue.put("D " + str(node.gridPos.x) + " " +
                                str(node.gridPos.y))
            return True
        return False

    # if a "home" was placed on the map.
    def on_home_added(self, node):
        if self.home != node:
            self.home = node
            self.send_queue.put("H " + str(node.gridPos.x) + " " +
                                str(node.gridPos.y))
            return True
        return False

    # If the start/stop button was pressed.
    def on_start_stop_clicked(self):
        self.toggle_in_motion()

    # switches the in_motion variable from true to false and vice versa.
    # It also changes the text of the start/stop button

    def toggle_in_motion(self):
        self.in_motion = not self.in_motion
        if self.in_motion:
            self.start_stop_button.setText("Stop")
            if len(self.simple_path) > 0:
                self.send_queue.put("GO")
        else:
            self.start_stop_button.setText("Start")
            self.send_queue.put("S")

    # noinspection PyArgumentList
    @pyqtSlot()
    def on_cam_on_off_clicked(self):
        button = self.cam_on_button
        if button.text() == "Turn Video On":
            button.setText("Turn Video Off")
            self.video.show()
        else:
            button.setText("Turn Video On")
            self.video.hide()

    # When the user wants to remove the destination
    def on_clear_destination_clicked(self):
        print("clearing destinations")
        if len(self.destinations) > 0:
            for d in self.destinations:
                self.remove_destination(d)
            self.destinations = []
            self.current_path = []
            self.simple_path = []
            self.send_queue.put("D -1 -1")
            self.grid_panel.redraw_grid()
            if self.in_motion:
                self.toggle_in_motion()

    def remove_destination(self, node):
        count = 0
        while self.grid_panel.buttons[count].node != node:
            count += 1
        self.grid_panel.buttons[count].setText("")

    # when auto/manual is toggled.
    # noinspection PyArgumentList
    @pyqtSlot()
    def on_autodrive_clicked(self):

        button = self.autodrive_button
        if button.text() == "Switch To Manual":
            button.setText("Switch To Automatic")
            self.client.remote_on = True
            self.start_stop_button.hide()
            self.send_queue.put("MODE 2")
            self.mode = MANUAL
        else:
            button.setText("Switch To Manual")
            if self.in_motion:
                self.on_start_stop_clicked()
            self.client.remote_on = False
            self.send_queue.put("S")
            self.start_stop_button.show()
            self.send_queue.put("MODE 0")
            self.mode = AUTO
        self.grid_panel.redraw_grid()

    # When the user tells the robot to go home.  drop everything and go home.
    # noinspection PyArgumentList
    @pyqtSlot()
    def on_go_home_clicked(self):
        if self.home is not None and self.rover_position != self.home:
            # set the current destination
            self.on_clear_destination_clicked()
            self.destinations.append(self.home)
            node = self.home
            self.send_queue.put("D " + str(node.gridPos.x) + " " +
                                str(node.gridPos.y))
            # if we aren't in automatic and going, we need to be.
            auto_button = self.autodrive_button
            if auto_button.text() == "Switch To Automatic":
                self.on_autodrive_clicked()
            if not self.in_motion:
                self.on_start_stop_clicked()
            self.send_queue.put("GO")
            self.grid_panel.redraw_grid()

    # this is a callback to signify that we have made it to a destination.
    # noinspection PyArgumentList
    @pyqtSlot()
    def on_point_reached(self):
        try:
            print("point reached - received from server")
            # if we are at our final destination, we are done.
            if len(self.destinations
                   ) > 0 and self.rover_position == self.destinations[0]:
                if len(self.destinations) > 0:
                    self.destinations.pop(0)

                if len(self.destinations) > 0:
                    print("Destination reached, going to next destination")

                else:
                    print("final destination reached")
                    self.send_queue.put("S")
                    if self.in_motion:
                        self.toggle_in_motion()
        except:
            print(traceback.format_exc())

    # a callback for when the rover's new position is sent.
    # noinspection PyArgumentList
    @pyqtSlot(Vector)
    def rover_pos_changed(self, position):
        node = self.grid.get_node(position.x, position.y)

        # we still only care if it moves it to a new node.
        if node != self.rover_position:
            print("rover position changed - Received from server")
            self.rover_position = node

        self.rover_coord_label.setText("Map Position: " + str(node.gridPos))
        self.grid_panel.redraw_grid()

    # opens a save dialog for the grid.
    def save(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getSaveFileName(
            self,
            "Save Grid",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        if file_name:
            print(file_name)

        self.grid.save(file_name)

    # opens a load dialog.
    def load(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "Load Grid",
            "",
            "All Files (*);;Python Files (*.py)",
            options=options)
        self.grid = Grid.load(file_name)
        self.grid_panel.setParent(None)
        self.grid_panel = None
        self.grid_panel = GridPanel(self, self.grid)
        self.grid_panel.show()
class SettWin(QWidget):

    listnames = ['Программа настройки',
                 'Восстановить настройки указателя по умолчанию',
                 'Посетить сайт', 'Сбросить настройки программы',
                 'Системная рамка окна утилиты']

    strtolist = 'Посетить сайт разработчика и автора программы, ' \
                'для получения дополнительной информации.'

    captions = ['Выполнить', 'Перейти', 'Сброс']

    def __init__(self, parent=None, *args, **kwargs):
        super(SettWin, self).__init__(parent, *args, **kwargs)
        self.setWindowTitle('Settings')
        self.getsettUI()

    def getsettUI(self):
        vbx = QVBoxLayout(self)
        self.grid = QGridLayout()
        self.hbox = QHBoxLayout()

        closeBtn = CloseButton()
        closeBtn.clicked.connect(lambda: self.parent().getPrevious(self))
        self.hbox.addWidget(closeBtn)
        self.btnh = closeBtn.sizeHint()

        vbx.addLayout(self.hbox)

        self.boxbuttons = QVBoxLayout()

        for caption in range(len(self.captions)):
            setBtns = ProjButton(self.captions[caption])
            setBtns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

            background = ['#eeeff7', '#9aa9d5']
            backimage = str('set_button2')

            if caption == 1:
                background = ['#4f587d', '#304563']
                backimage = 'set_button1'

            setBtns.setStyleSheet('''
                QPushButton{
                    background:%s url(accessory/images/%s.png);
                    border-radius:18px;background-repeat:no-repeat;
                    background-position:left;background-origin:content;
                    padding-left:0.4em;font:bold 12px;color:#2b2e36;
                }
                QPushButton::pressed{
                    background:%s url(accessory/images/%s_Active.png);
                    background-repeat:no-repeat;
                    background-position:left;
                }''' % (background[0], backimage, background[1], backimage))

            setBtns.setMaximumSize(170, 42)
            setBtns.setMinimumSize(setBtns.size())
            setBtns.clicked.connect(partial(self.getvalBtns, caption))
            self.boxbuttons.addWidget(setBtns)

        setcheckn = QCheckBox()
        """Проверка на существование обозначения, в файле настроек,
            программы `configfile.ini`"""
        checkstate = getPar().settings.value('checkstate')
        if checkstate is not None:
            setcheckn.setCheckState(int(checkstate))
        else:
            setcheckn.setCheckState(Qt.Checked)

        setcheckn.setCursor(Qt.PointingHandCursor)
        setcheckn.setStyleSheet("""
            QCheckBox::indicator{
                background-color:#eeeff7;
                border:3px solid #4f587d;
                width:20px;height:20px;
            }
            QCheckBox::indicator:checked{
                image:url(accessory/images/check.png);
            }""")
        setcheckn.resize(20,20)
        setcheckn.setMinimumSize(setcheckn.size())
        setcheckn.stateChanged.connect(getPar().clickBox)
        self.boxbuttons.addWidget(setcheckn, 1, Qt.AlignHCenter)

        self.boxbuttons.setSpacing(30)
        vbx.addLayout(self.boxbuttons)
        self.setLayout(vbx)

    def getvalBtns(self, val):
        if val == 0:

            dlg = QDialog(self, Qt.Dialog |
                          Qt.WindowTitleHint | Qt.WindowCloseButtonHint)
            dlg.setStyleSheet('''background-color:#81848c;''')
            dlg.resize(dlg.width() * 2.5, dlg.height() * 3.2)

            buttonBox = QDialogButtonBox(QDialogButtonBox.Ok)
            buttonBox.setCursor(Qt.PointingHandCursor)
            buttonBox.setStyleSheet('''
                QPushButton{
                    background-color:#585b63;font-size:13px;
                    border:1px solid #21242c;padding:0.2em 0;
                    width:60px;
                }
                QPushButton::pressed{
                    background-color:#76798e;color:#ffffff;
                    border-color:#a3a6bb;
                }''')

            buttonBox.setCenterButtons(True)
            buttonBox.accepted.connect(dlg.close)

            lbl = QLabel('Системные настройки указателя востнановленны.')
            lbl.setAlignment(Qt.AlignCenter)
            fnt = QFont('Helvetica, Arial, sans-serif', 10)
            fnt.setBold(True)
            lbl.setFont(fnt)
            lbl.setWordWrap(True)

            vlayout = QVBoxLayout()
            vlayout.addWidget(lbl)
            vlayout.addWidget(buttonBox)

            dlg.setLayout(vlayout)
            dlg.exec_()
        elif val == 1:
            launch_webbrowser('https://pcompstart.com/')
        elif val == 2:
            # QDialog - контейнер для кнопок
            dlg = QDialog(self, Qt.Dialog |
                          Qt.WindowTitleHint | Qt.WindowCloseButtonHint)
            dlg.setStyleSheet('''background-color:#81848c;''')
            dlg.resize(dlg.width() * 2.5, dlg.height() * 3.2)

            """`ProjButton` создание кнопки для преврашения
                в последующее пустое место, между кнопками в
                `QDialogButtonBox`"""
            projbutton = ProjButton('')

            # `QDialogButtonBox` - кнопки `Reset` и `Cancel`
            buttonBox = QDialogButtonBox(QDialogButtonBox.Cancel)
            buttonBox.addButton('Reset', QDialogButtonBox.AcceptRole)
            buttonBox.addButton(projbutton, QDialogButtonBox.ActionRole)
            buttonBox.setCursor(Qt.PointingHandCursor)
            buttonBox.setStyleSheet('''
                QPushButton{
                    background-color:#585b63;font-size:13px;
                    border:1px solid #21242c;padding:0.2em 0;
                    width:60px;
                }
                QPushButton::pressed{
                    background-color:#76798e;color:#ffffff;
                    border-color:#a3a6bb;
                }''')

            projbutton.setCursor(Qt.ArrowCursor)
            projbutton.setStyleSheet('''
                background:transparent;border:transparent;
                width:20px;''')

            buttonBox.setCenterButtons(True)
            buttonBox.accepted.connect(self.on_quit)
            buttonBox.rejected.connect(dlg.close)

            lbl = QLabel('После сброса, требуется перезапустить программу.')
            lbl.setAlignment(Qt.AlignCenter)
            fnt = QFont('Helvetica, Arial, sans-serif', 10)
            fnt.setBold(True)
            lbl.setFont(fnt)
            lbl.setWordWrap(True)

            vlayout = QVBoxLayout()
            vlayout.addWidget(lbl)
            vlayout.addWidget(buttonBox)

            dlg.setLayout(vlayout)
            dlg.exec_()

    def resizeEvent(self, event):
        # self.evh отступ 50 px от верха окна
        parheight = event.size().height()
        parwidth = event.size().width()
        self.evh = parheight / 13
        ymarg = (self.evh / 2) - (self.btnh.height() / 2)
        xmarg = (self.width() - self.btnh.width()) / 1.01
        self.hbox.setGeometry(QRect(
            xmarg, ymarg, self.btnh.width(), self.btnh.height()))

        self.boxbuttons.setGeometry(QRect(
            parwidth / 1.4, parheight / 40,
            190, parheight))

    # def closeEvent(self, closeEv):
    #     print(qApp.children())
    #     closeEv.ignore()


    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.drawLines(qp)
        qp.end()

    def drawLines(self, qp):
        pen = QPen(QColor('#eeeff7'), 2, Qt.SolidLine)
        qp.setPen(pen)

        font = QFont('Arial', 19)
        qp.setFont(font)

        # first - растояние первой линии от верха
        first = self.evh
        qp.drawLine(self.x(), first, self.width(), first)

        # Отрисовка главного заголовка настроек
        # Функция возвращающая верхнюю середину ширины окна для подзаголовка
        def getPosxTitle(name):
            wn = qp.fontMetrics().width(name)
            return (self.width() / 2) - (wn / 2)

        pos_x_title = getPosxTitle(self.listnames[0])

        # Условие описания уменьшения названия при уменьшении высоты
        if self.height() < self.parent().baseSize().height():
            fontsize = (first - font.pointSizeF()) / 1.6
            if self.height() <= 550:
                fontsize = 14

            font.setPointSizeF(fontsize)
            qp.setFont(font)
            pos_x_title = getPosxTitle(self.listnames[0])

        qp.drawText(pos_x_title, first / 1.55, self.listnames[0])

        # distance = 150 дистанция между остальными линиями
        distance = (self.height() - first) / 4
        i = 0
        '''leftIndent - маштабируемый отступ от левой стороны окна,
            для названий категорий настроек'''
        leftIndent = qp.viewport().width() / 9

        while first < self.height() and i < len(self.listnames[1:]):
            first += distance
            i += 1
            qp.setPen(QColor('#9fcdd0'))
            font.setPointSize(16)

            # ширина квадрата в котором написано название категории
            # widthrect = 240
            widthrect = 240

            # размер маленького шрифта
            smallfnt = 10

            if self.height() < self.parent().baseSize().height():
                if self.height() <= 550:
                    font.setPointSize(13)
                    widthrect = 220
                    smallfnt = 8
                else:
                    font.setPointSizeF(distance / font.pointSizeF() * 1.72)
            qp.setFont(font)

            # posvcen - вычисление маштабируемого отступа по выстое
            posvcen = lambda a: distance / a + qp.fontMetrics().height()
            if i == 2:
                qp.drawText(
                    leftIndent - 5, first - posvcen(1.55), widthrect, distance / 2,
                    Qt.TextWordWrap | Qt.AlignHCenter|Qt.AA_EnableHighDpiScaling, self.listnames[i])

                qp.setPen(QColor('#eeeff7'))
                # font.setPointSize(smallfnt)
                font.setPointSize(smallfnt)
                font.setItalic(True)
                qp.setFont(font)
                qp.drawText(
                    leftIndent, first - posvcen(2.15), 230, distance / 2,
                    Qt.TextWordWrap | Qt.AlignHCenter|Qt.AA_EnableHighDpiScaling, self.strtolist)
            else:
                font.setItalic(False)
                qp.setFont(font)
                qp.drawText(
                    leftIndent, first - posvcen(2), widthrect, distance / 2,
                    Qt.TextWordWrap | Qt.AlignHCenter|Qt.AA_EnableHighDpiScaling, self.listnames[i])
            # отрисовка линий
            if first >= self.height():
                continue
            else:
                qp.setPen(pen)
                qp.drawLine(self.rect().x(), first, self.width(), first)

    def on_quit(self):
        confpath = '{}/accessory/configfile.ini'.format(os.getcwd())
        if os.path.exists(confpath):
            os.remove(confpath)
        qApp.quit()
    def __init__(self):
        print("start")
        QWidget.__init__(self)

        self.setMinimumSize(QSize(600, 500))
        self.setWindowTitle("Stereo_vision")
        self.figure = plt.figure(figsize=(
            0,
            2,
        ),
                                 facecolor='y',
                                 edgecolor='r')  #  color only
        self.canvas = FigureCanvas(self.figure)
        self.figure.subplots_adjust(0.2, 0.4, 0.8, 1)
        pybutton = QPushButton('graph', self)

        pybutton_data = QPushButton('print_settings', self)

        global axis_x
        axis_x = 0
        pybutton.clicked.connect(self.clickMethod)
        pybutton.move(50, 10)
        pybutton.resize(100, 32)
        layout = QVBoxLayout()
        layout.setContentsMargins(50, 100, 0, 11)  # move background
        layout.setGeometry(QRect(0, 0, 80, 68))  # nothing
        layout.addWidget(self.canvas)

        pybutton_data.clicked.connect(self.settings)
        pybutton_data.move(50, 50)
        pybutton_data.resize(100, 32)
        layout = QVBoxLayout()
        layout.setContentsMargins(50, 100, 0, 11)  # move background
        layout.setGeometry(QRect(0, 0, 80, 68))  # nothing
        layout.addWidget(self.canvas)

        # input dataufoff value
        self.le_num1 = QLineEdit()
        self.le_num1.setFixedSize(50, 20)  # size
        self.le_num1.move(100, 110)
        self.pb_num1 = QPushButton('minDisparity')
        self.pb_num1.setFixedSize(150, 60)  # size
        self.pb_num1.clicked.connect(self.show_dialog_num1)
        self.pb_num1.move(100, 110)
        #    layout.addWidget(self.le_num1)
        layout.addWidget(self.pb_num1)
        self.setLayout(layout)
        # stop input data
        # start input data fps
        self.le_num2 = QLineEdit()
        self.le_num2.setFixedSize(50, 20)  # size
        self.pb_num2 = QPushButton('numDisparities')
        self.pb_num2.setFixedSize(150, 60)  # size
        self.pb_num2.clicked.connect(self.show_dialog_num2)
        # layout.addWidget(self.le_num2)
        self.pb_num2.move(90, 100)
        layout.addWidget(self.pb_num2)
        self.setLayout(layout)
        # stop input data fps
        # start input data low filter
        self.le_num3 = QLineEdit()
        self.le_num3.setFixedSize(50, 20)  # size
        self.pb_num3 = QPushButton('blockSize')
        self.pb_num3.setFixedSize(150, 60)  # size
        self.pb_num3.clicked.connect(self.show_dialog_num3)
        #  layout.addWidget(self.le_num3)
        self.pb_num3.move(190, 100)
        layout.addWidget(self.pb_num3)
        self.setLayout(layout)
        # stop input data filter
        #disp12MaxDiff
        self.le_num4 = QLineEdit()
        self.le_num4.setFixedSize(50, 20)  # size
        self.pb_num4 = QPushButton('disp12MaxDiff')
        self.pb_num4.setFixedSize(150, 60)  # size
        self.pb_num4.clicked.connect(self.show_dialog_num4)
        #   layout.addWidget(self.le_num4)
        self.pb_num4.move(90, 200)
        layout.addWidget(self.pb_num4)
        self.setLayout(layout)
        #uniquenessRatio
        self.le_num5 = QLineEdit()
        self.le_num5.setFixedSize(50, 20)  # size
        self.pb_num5 = QPushButton('uniquenessRatio')
        self.pb_num5.setFixedSize(150, 60)  # size
        self.pb_num5.clicked.connect(self.show_dialog_num5)
        # layout.addWidget(self.le_num5)
        self.pb_num5.move(190, 200)
        layout.addWidget(self.pb_num5)
        self.setLayout(layout)
        #speckleWindowSize
        self.le_num6 = QLineEdit()
        self.le_num6.setFixedSize(50, 20)  # size
        self.pb_num6 = QPushButton('speckleWindowSize')
        self.pb_num6.setFixedSize(150, 60)  # size
        self.pb_num6.clicked.connect(self.show_dialog_num6)
        #layout.addWidget(self.le_num6)
        self.pb_num6.move(290, 200)
        layout.addWidget(self.pb_num6)
        self.setLayout(layout)
        #speckleRange
        self.le_num7 = QLineEdit()
        self.le_num7.setFixedSize(50, 20)  # size
        self.pb_num7 = QPushButton('speckleRange')
        self.pb_num7.setFixedSize(150, 60)  # size
        self.pb_num7.clicked.connect(self.show_dialog_num7)
        #layout.addWidget(self.le_num7)
        self.pb_num7.move(390, 200)
        layout.addWidget(self.pb_num7)
        self.setLayout(layout)
Esempio n. 9
0
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        dialwidth = self.geometry().width() * 0.04
        LabelFont = QtGui.QFont('Arial', 14)
        self.dividerRatio = 0.3

        self.Platform = 2
        self.gtv = 0
        self.gtvp = 2

        self._gauge1 = RadialBar(self)
        self._gauge1.foregroundColor = QtGui.QColor("#181c24")
        self._gauge1.dialWidth = dialwidth
        self._gauge1.startAngle = 90
        self._gauge1.spanAngle = 180
        self._gauge1.textColor = QtGui.QColor("#FFFFFF")
        self._gauge1.penStyle = QtCore.Qt.RoundCap
        self._gauge1.dialType = RadialBar.DialType.MinToMax
        self._gauge1.suffixText = ""
        self._gauge1.maxValue = 200
        self._gauge1.minValue = 0
        self._gauge1.value = 0
        self.myfont = QtGui.QFont()
        #self._gauge1.textFont = self.myfont
        self._gauge1._normalMinValue = 70
        self._gauge1._normalMaxValue = 120

        self._gauge2 = RadialBar(self)
        self._gauge2.foregroundColor = QtGui.QColor("#181c24")
        self._gauge2.dialWidth = dialwidth
        self._gauge2.startAngle = 90
        self._gauge2.spanAngle = 180
        self._gauge2.textColor = QtGui.QColor("#FFFFFF")
        self._gauge2.penStyle = QtCore.Qt.RoundCap
        self._gauge2.dialType = RadialBar.DialType.MinToMax
        self._gauge2.suffixText = ""
        self._gauge2.maxValue = 100
        self._gauge2.minValue = 0
        self._gauge2.value = 0
        self._gauge2._normalMinValue = 90
        self._gauge2._normalMaxValue = 100
        #self._gauge2.textFont = self.myfont

        self._gauge3 = RadialBar(self)
        self._gauge3.foregroundColor = QtGui.QColor("#181c24")
        self._gauge3.dialWidth = dialwidth
        self._gauge3.startAngle = 90
        self._gauge3.spanAngle = 180
        self._gauge3.textColor = QtGui.QColor("#FFFFFF")
        self._gauge3.penStyle = QtCore.Qt.RoundCap
        self._gauge3.dialType = RadialBar.DialType.MinToMax
        self._gauge3.suffixText = ""
        self._gauge3.maxValue = 40
        self._gauge3.minValue = 5
        self._gauge3.value = 0
        self._gauge3._normalMinValue = 11
        self._gauge3._normalMaxValue = 18
        #self._gauge3.textFont = self.myfont

        self._gauge4 = RadialBar(self)
        self._gauge4.foregroundColor = QtGui.QColor("#181c24")
        self._gauge4.dialWidth = dialwidth
        self._gauge4.startAngle = 90
        self._gauge4.spanAngle = 180
        self._gauge4.textColor = QtGui.QColor("#FFFFFF")
        self._gauge4.penStyle = QtCore.Qt.RoundCap
        self._gauge4.dialType = RadialBar.DialType.MinToMax
        self._gauge4.suffixText = ""
        self._gauge4.maxValue = 100
        self._gauge4.minValue = 0
        self._gauge4.value = 0
        self._gauge4._normalMinValue = 80
        self._gauge4._normalMaxValue = 100
        #self._gauge4.textFont = self.myfont

        self.vbox = QVBoxLayout()
        self.vbox.setContentsMargins(self.geometry().height() * 0.087, 10, 10,
                                     10)  # Centers Gauges

        self.LabelHeading = QtWidgets.QLabel("Sensor Data")
        self.label1 = QtWidgets.QLabel("Heart Rate")
        self.label2 = QtWidgets.QLabel("Blood Oxygen")
        self.label3 = QtWidgets.QLabel("Breath per Minute")
        self.label4 = QtWidgets.QLabel("Lung Capacity")

        self.label1.setFont(LabelFont)
        self.label2.setFont(LabelFont)
        self.label3.setFont(LabelFont)
        self.label4.setFont(LabelFont)
        self.LabelHeading.setFont(LabelFont)

        self.label1.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.label2.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.label3.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.label4.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.LabelHeading.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")

        self.label1.setAlignment(QtCore.Qt.AlignCenter)
        self.label2.setAlignment(QtCore.Qt.AlignCenter)
        self.label3.setAlignment(QtCore.Qt.AlignCenter)
        self.label4.setAlignment(QtCore.Qt.AlignCenter)
        self.LabelHeading.setAlignment(QtCore.Qt.AlignCenter)

        #label1.setContentsMargins(self.geometry().height() * 0.11 -(self.geometry().width() *0.005 ), 10, 10, 10)
        #label1.setAlignment(QtCore.Qt.AlignCenter)

        self.vbox.addWidget(self.LabelHeading)
        self.vbox.addSpacing(45)
        self.vbox.addWidget(self.label1)
        self.vbox.addWidget(self._gauge1, 1)
        self.vbox.addStretch()
        self.vbox.addWidget(self.label2)
        self.vbox.addWidget(self._gauge2, 1)
        self.vbox.addStretch()
        self.vbox.addWidget(self.label3)
        self.vbox.addWidget(self._gauge3, 1)
        self.vbox.addStretch()
        self.vbox.addWidget(self.label4)
        self.vbox.addWidget(self._gauge4, 1)
        self.vbox.addStretch()
        self.vrect = QtCore.QRect(
            0, 0, (self.geometry().height() * self.dividerRatio),
            self.geometry().height())
        self.vbox.setGeometry(self.vrect)

        self.GraphicsWindow = QVBoxLayout()
        #GraphicsWindow.addStretch()
        #vrectGW = QtCore.QRect((self.geometry().width()*0.3), 0, (self.geometry().width()*1.5), self.geometry().height())
        #GraphicsWindow.setGeometry(vrectGW);

        self.debugWindow = QtWidgets.QLabel()
        self.debugWindow.setSizePolicy(QtWidgets.QSizePolicy.Maximum,
                                       QtWidgets.QSizePolicy.Fixed)
        #debugWindow.setSizePolicy(QtWidgets.QSizePolicy.Expanding,QtWidgets.QSizePolicy.Fixed)
        self.debugWindow.setStyleSheet(
            "background-color: white; padding: 4px; qproperty-alignment: AlignRight; margin-left:50%;"
        )
        self.debugWindow.setText("Debug Window")
        self._debugWindow = QtWidgets.QHBoxLayout()
        self._debugWindow.addSpacerItem(
            QtWidgets.QSpacerItem(250, 10, QtWidgets.QSizePolicy.Expanding))
        self._debugWindow.addWidget(self.debugWindow)

        self.usermsg = QtWidgets.QLabel()
        self.usermsg.setText("Max Temperature: 0")
        self.usermsg.setFont(self.myfont)
        self.usermsg.setAlignment(QtCore.Qt.AlignCenter)
        self.usermsg.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")

        self.Instructions = QtWidgets.QLabel()
        self.Instructions.setText("Ready")
        self.Instructions.setFont(self.myfont)
        self.Instructions.setAlignment(QtCore.Qt.AlignCenter)
        self.Instructions.setStyleSheet(
            "color: orange; padding-bottom:10px; text-align: center;")

        self.fr_id = QtWidgets.QLabel()
        self.fr_id.setText("Last Record Sno: None")
        self.fr_id.setFont(self.myfont)
        self.fr_id.setAlignment(QtCore.Qt.AlignCenter)
        self.fr_id.setStyleSheet(
            "color: orange; padding-bottom:10px; text-align: center;")

        self.messagepanellayout = QVBoxLayout()
        self.messagepanellayout.addSpacerItem(
            QtWidgets.QSpacerItem(250, 100, QtWidgets.QSizePolicy.Expanding))
        self.messagepanellayout.addWidget(self.Instructions)
        self.messagepanellayout.addSpacerItem(
            QtWidgets.QSpacerItem(250, 100, QtWidgets.QSizePolicy.Expanding))
        self.messagepanellayout.addWidget(self.usermsg)
        self.messagepanellayout.addSpacerItem(
            QtWidgets.QSpacerItem(250, 100, QtWidgets.QSizePolicy.Expanding))
        self.messagepanellayout.addWidget(self.fr_id)
        self.messagepanellayout.addSpacerItem(
            QtWidgets.QSpacerItem(250, 100, QtWidgets.QSizePolicy.Expanding))

        self.CVPanel = QHBoxLayout()
        self.CVPanel.addLayout(self.messagepanellayout)

        self.CVPanelHeading = QHBoxLayout()
        self.H1 = QtWidgets.QLabel()
        self.H1.setText("Thermal Feed")
        self.H1.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.H2 = QtWidgets.QLabel()
        self.H2.setText("Info Panel")
        self.H2.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.CVPanelHeading.addSpacerItem(
            QtWidgets.QSpacerItem(70, 10, QtWidgets.QSizePolicy.Maximum))
        self.CVPanelHeading.addWidget(self.H1)
        self.CVPanelHeading.addSpacerItem(
            QtWidgets.QSpacerItem(250, 10, QtWidgets.QSizePolicy.Expanding))
        self.CVPanelHeading.addWidget(self.H2)
        self.CVPanelHeading.addSpacerItem(
            QtWidgets.QSpacerItem(250, 10, QtWidgets.QSizePolicy.Expanding))

        self.InfoPanelLabels = QHBoxLayout()
        self.i1 = QtWidgets.QLabel()
        self.i1.setText("Face Recognition")
        self.i1.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.i2 = QtWidgets.QLabel()
        self.i2.setText("Lungs Displacement")
        self.i2.setStyleSheet(
            "color: white; padding-bottom:10px; text-align: center;")
        self.InfoPanelLabels.addSpacerItem(
            QtWidgets.QSpacerItem(70, 10, QtWidgets.QSizePolicy.Maximum))
        self.InfoPanelLabels.addWidget(self.i1)
        self.InfoPanelLabels.addSpacerItem(
            QtWidgets.QSpacerItem(250, 10, QtWidgets.QSizePolicy.Expanding))
        self.InfoPanelLabels.addWidget(self.i2)
        self.InfoPanelLabels.addSpacerItem(
            QtWidgets.QSpacerItem(250, 10, QtWidgets.QSizePolicy.Expanding))

        self.InfoPanel = QHBoxLayout()
        self.graphWidget = pg.PlotWidget()
        self.GraphY = [0, 0]
        self.GraphX = [0, 0]
        self.graphWidget.setYRange(-10, 10, padding=0)
        #self.graphWidget.setXRange(0, 10, padding=0)

        self.GraphBorder = QtWidgets.QVBoxLayout()
        self.GraphBorder.addWidget(self.graphWidget)

        self.InfoPanel.addSpacerItem(
            QtWidgets.QSpacerItem(70, 10, QtWidgets.QSizePolicy.Maximum))
        self.InfoPanel.addWidget(self.fr)
        self.InfoPanel.addSpacerItem(
            QtWidgets.QSpacerItem(25, 10, QtWidgets.QSizePolicy.Expanding))
        self.InfoPanel.addLayout(self.GraphBorder)
        self.InfoPanel.addSpacerItem(
            QtWidgets.QSpacerItem(25, 10, QtWidgets.QSizePolicy.Expanding))
        #InfoPanel.setAlignment(QtCore.Qt.AlignRight)

        self.startscanM = QtWidgets.QPushButton("Start Scan - Male")
        self.startscanF = QtWidgets.QPushButton("Start Scan - Female")
        self.startscanM.clicked.connect(self.RunScanM)
        self.startscanF.clicked.connect(self.RunScanF)
        self.controls = QtWidgets.QHBoxLayout()
        self.controls.addSpacerItem(
            QtWidgets.QSpacerItem(25, 10, QtWidgets.QSizePolicy.Expanding))
        self.controls.addWidget(self.startscanM)
        self.controls.addSpacerItem(
            QtWidgets.QSpacerItem(25, 10, QtWidgets.QSizePolicy.Expanding))
        self.controls.addWidget(self.startscanF)
        self.controls.addSpacerItem(
            QtWidgets.QSpacerItem(25, 10, QtWidgets.QSizePolicy.Expanding))

        self.GraphicsWindow.addLayout(self.CVPanelHeading)
        self.GraphicsWindow.addLayout(self.CVPanel)
        self.GraphicsWindow.addSpacerItem(
            QtWidgets.QSpacerItem(250, 40, QtWidgets.QSizePolicy.Maximum))
        self.GraphicsWindow.addLayout(self.InfoPanelLabels)
        self.GraphicsWindow.addSpacerItem(
            QtWidgets.QSpacerItem(250, 60, QtWidgets.QSizePolicy.Minimum))
        self.GraphicsWindow.addLayout(self.InfoPanel)
        self.GraphicsWindow.addSpacerItem(
            QtWidgets.QSpacerItem(250, 40, QtWidgets.QSizePolicy.Maximum))
        self.GraphicsWindow.addLayout(self.controls)
        self.GraphicsWindow.addStretch()
        self.GraphicsWindow.addLayout(self._debugWindow)

        self._gauge1.value = self.gtv
        self._gauge2.value = self.gtv
        self._gauge3.value = self.gtv
        self._gauge4.value = self.gtv

        self.hbox = QHBoxLayout()
        self.hbox.setContentsMargins(self.geometry().height() * 0.1, 10, 10,
                                     10)
        self.hbox.addLayout(self.vbox)
        self.hbox.addStretch()
        self.hbox.addLayout(self.GraphicsWindow)

        self.setLayout(self.hbox)

        #painter = QtGui.QPainter(self)

        #brush = QtGui.QBrush()

        self.setMinimumSize(900, 600)
        self.showMaximized()
        self.setWindowTitle('Dashboard')

        self.scanthread = HandleScan()
        self.scanthread.setGaugeParams(
            self._gauge1._normalMinValue, self._gauge1._normalMaxValue,
            self._gauge2._normalMinValue, self._gauge2._normalMaxValue,
            self._gauge3._normalMinValue, self._gauge3._normalMaxValue,
            self._gauge4._normalMinValue, self._gauge4._normalMaxValue)

        self.show()

    def gomessage(self):
        self.Instructions.setStyleSheet(
            "color: green; padding-bottom:10px; text-align: center;")
        self.setmsg("Test Negative\nGo")

    def stopmessage(self):
        self.Instructions.setStyleSheet(
            "color: red; padding-bottom:10px; text-align: center;")
        self.setmsg("Test Positive\nStop")

    def setmsg(self, str):
        self.Instructions.setText(str)

    def setdebugwin(self, str):
        self.debugWindow.setText(str)

    def RunScanM(self):
        self.scanthread.start()
        self.connectscansignals()
        self.scanthread.startscan(True, 0)

    def RunScanF(self):
        self.scanthread.start()
        self.connectscansignals()
        self.scanthread.startscan(True, 1)

    def setgauge1val(self, val):
        self._gauge1.value = val

    def setgauge2val(self, val):
        self._gauge2.value = val

    def setgauge3val(self, val):
        self._gauge3.value = val

    def setgauge4val(self, val):
        self._gauge4.value = val

    def setinstruction(self, str):
        self.Instructions.setText(str)

    def setlivetemp(self, val):
        self.usermsg.setText(str(val))

    def cleargraph(self):
        self.graphWidget.clear()

    def setgraph(self, val_list):
        self.GraphY = val_list[0]
        self.GraphX = val_list[1]
        #self.graphWidget.plot(val_list[1], val_list[0])

    def trigFRTrain(self, val):
        if val:
            self.fr.face_detection_widget.CheckTrainTrigger()

    def resFRTraintrig(self, val):
        if val:
            self.fr.face_detection_widget.resMeanFRSession()

    def connectscansignals(self):
        self.scanthread._gauge1value.connect(self.setgauge1val)
        self.scanthread._gauge2value.connect(self.setgauge2val)
        self.scanthread._gauge3value.connect(self.setgauge3val)
        self.scanthread._gauge4value.connect(self.setgauge4val)
        self.scanthread.InstructionssetText.connect(self.setinstruction)
        self.scanthread.debugWindowsetText.connect(self.setdebugwin)
        self.scanthread.usermsgsetText.connect(self.setlivetemp)
        self.scanthread.graphWidgetclear.connect(self.cleargraph)
        self.scanthread.graphdata.connect(self.setgraph)
        self.scanthread.checktraintrigger.connect(self.trigFRTrain)
        self.scanthread.restraintrig.connect(self.resFRTraintrig)

    def paintEvent(self, e):
        #self.fd.face_detection_widget.update()
        self.fr.face_detection_widget.update()
        #self.fd.update()
        self.fr.update()

        painter = QtGui.QPainter(self)

        self.brush = QtGui.QBrush()

        self.brush.setColor(QtGui.QColor('#242a30'))
        self.brush.setStyle(QtCore.Qt.SolidPattern)
        self.rect = QtCore.QRect(0, 0,
                                 painter.device().height() * self.dividerRatio,
                                 painter.device().height())
        painter.fillRect(self.rect, self.brush)

        self.brush.setColor(QtGui.QColor('#363a42'))
        self.brush.setStyle(QtCore.Qt.SolidPattern)
        self.rect = QtCore.QRect(painter.device().height() * self.dividerRatio,
                                 0,
                                 painter.device().width(),
                                 painter.device().height())
        painter.fillRect(self.rect, self.brush)
        #self.debugWindow.adjustSize()

        self.myfont = QtGui.QFont()
        self.myfont.setPixelSize(painter.device().height() * 0.032)
        dw = painter.device().height() * 0.022
        sclabelfont = QtGui.QFont('Arial', (painter.device().height() * 0.012))
        sclabelfontH = QtGui.QFont('Arial',
                                   (painter.device().height() * 0.016))
        sclabelfontH1 = QtGui.QFont('Arial',
                                    (painter.device().height() * 0.016))
        self.vrecti = QtCore.QRect(0, 0, (painter.device().height() * 0.29),
                                   painter.device().height())

        self.vbox.setContentsMargins(painter.device().height() * 0.06, 10, 10,
                                     10)  # Centers Gauges
        self.vbox.setGeometry(self.vrecti)
        self._gauge1.textFont = self.myfont
        self._gauge2.textFont = self.myfont
        self._gauge3.textFont = self.myfont
        self._gauge4.textFont = self.myfont
        self._gauge1.dialWidth = dw
        self._gauge2.dialWidth = dw
        self._gauge3.dialWidth = dw
        self._gauge4.dialWidth = dw
        self.label1.setFont(sclabelfont)
        self.label2.setFont(sclabelfont)
        self.label3.setFont(sclabelfont)
        self.label4.setFont(sclabelfont)
        self.LabelHeading.setFont(sclabelfontH)
        self.usermsg.setFont(sclabelfontH1)
        self.Instructions.setFont(sclabelfontH1)
        self.H1.setFont(sclabelfont)
        self.H2.setFont(sclabelfont)
        self.i1.setFont(sclabelfont)
        self.i2.setFont(sclabelfont)
        self.Instructions.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                        QtWidgets.QSizePolicy.Maximum)
        self.usermsg.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Maximum)
        self.debugWindow.setMaximumSize((painter.device().width() * 0.75),
                                        painter.device().height() * 0.03)
        self.debugWindow.setMinimumSize((painter.device().width() * 0.75),
                                        painter.device().height() * 0.03)
        self.GraphBorder.setGeometry(
            QtCore.QRect(painter.device().width() * 0.62,
                         painter.device().height() * 0.55,
                         painter.device().width() * 0.35,
                         painter.device().height() * 0.35))
        self.fr.setGeometry(
            QtCore.QRect(painter.device().width() * 0.25,
                         painter.device().height() * 0.55,
                         painter.device().width() * 0.35,
                         painter.device().height() * 0.35))
        #self.fd.face_detection_widget.setGeometry(QtCore.QRect(painter.device().width()*0.25, painter.device().height()*0.06, painter.device().width()*0.35, painter.device().height()*0.35))
        self.messagepanellayout.setGeometry(
            QtCore.QRect(painter.device().width() * 0.62,
                         painter.device().height() * 0.06,
                         painter.device().width() * 0.35,
                         painter.device().height() * 0.35))

        self.Instructions.setStyleSheet(
            "color: orange; padding-bottom:10px; text-align: center;")
        # plot data: x, y values
        self.graphWidget.clear()
        self.graphWidget.plot(self.GraphX, self.GraphY)

        self.ttemp = self.fd.face_detection_widget.gettemp()
        self.scanthread.updatetemp(self.ttemp)
Esempio n. 10
0
class Ui_Form(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.suanfa = 1
        self.init_ui()

    def init_ui(self):
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/data/ico.ico"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.setObjectName("清华大学得不到的学生")
        self.setWindowTitle("一只小可爱~")
        self.resize(1274, 677)
        self.label = QLabel(self)
        self.label.setWindowTitle("清华大学得不到的学生")
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.label.setGeometry(QtCore.QRect(15, 15, 1244, 647))
        self.label.setText("")
        palette = QtGui.QPalette()

        self.label.setStyleSheet("background-color: #fff;border-radius: 15px;")
        self.labelshadow = QGraphicsDropShadowEffect(self)
        self.labelshadow.setBlurRadius(15)
        self.labelshadow.setOffset(1, 1)
        self.label.setGraphicsEffect(self.labelshadow)

        self.label.setScaledContents(True)
        self.label.setObjectName("label")

        self.pushButton_12 = QtWidgets.QPushButton(self)
        self.pushButton_12.setGeometry(
            QtCore.QRect(self.width() - 55, 29, 20, 20))
        self.pushButton_12.setStyleSheet(
            "QPushButton{\n"
            "    background:#fc625d;\n"
            "    color:white;\n"
            "    box-shadow: 1px 1px 3px rgba(0,0,0,0.3);font-size:20px;border-radius: 10px;font-family: 微软雅黑;\n"
            "}\n"
            "QPushButton:hover{                    \n"
            "    background:#FF2D2D;\n"
            "}\n"
            "QPushButton:pressed{\n"
            "    border: 1px solid #3C3C3C!important;\n"
            "    background:#AE0000;\n"
            "}")
        self.pushButton_12.clicked.connect(QCoreApplication.instance().quit)

        self.pushButton_14 = QtWidgets.QPushButton(self)
        self.pushButton_14.setGeometry(
            QtCore.QRect(self.width() - 55 - 35, 29, 20, 20))
        self.pushButton_14.setStyleSheet(
            "QPushButton{\n"
            "    background:#35cd4b;\n"
            "    color:white;\n"
            "    box-shadow: 1px 1px 3px rgba(0,0,0,0.3);font-size:20px;border-radius: 10px;font-family: 微软雅黑;\n"
            "}\n"
            "QPushButton:hover{                    \n"
            "    background:#00CC00;\n"
            "}\n"
            "QPushButton:pressed{\n"
            "    border: 1px solid #3C3C3C!important;\n"
            "    background:#009900;\n"
            "}")
        self.pushButton_14.clicked.connect(self.showMinimized)

        self.pushButton_15 = QtWidgets.QPushButton(self)
        self.pushButton_15.setGeometry(QtCore.QRect(70, 70, 240, 50))
        self.pushButton_15.setStyleSheet(
            "QPushButton{background-color: #7fa6c8; font-family: 微软雅黑;" +
            "border: none;" + "color: #fff;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")
        self.pushButton_15.setText("先进先出算法-FIFO")
        self.pushButton_15.clicked.connect(self.on_click)

        self.pushButton_16 = QtWidgets.QPushButton(self)
        self.pushButton_16.setGeometry(QtCore.QRect(70, 150, 240, 50))
        self.pushButton_16.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")
        self.pushButton_16.setText("最近最久未使用算法-LRU")
        self.pushButton_16.clicked.connect(self.on_click_two)

        self.pushButton_17 = QtWidgets.QPushButton(self)
        self.pushButton_17.setGeometry(QtCore.QRect(70, 230, 240, 50))
        self.pushButton_17.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")
        self.pushButton_17.setText("理想型淘汰算法-OPT")
        self.pushButton_17.clicked.connect(self.on_click_three)

        self.biaoti = QLabel(self)
        self.biaoti.setGeometry(QtCore.QRect(370, 70, 480, 50))
        self.biaoti.setStyleSheet(
            "background-color: #f0f0f0;border-radius: 7px;")

        self.biaoti_one = QtWidgets.QPushButton(self)
        self.biaoti_one.setGeometry(QtCore.QRect(375, 75, 230, 40))
        self.biaoti_one.setStyleSheet(
            "QPushButton{background-color: white; font-family: 微软雅黑;" +
            "border: none; " + "color: #000;border-radius: 5px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")

        self.biaotipos = 1
        self.biaoti_two = QtWidgets.QPushButton(self)
        self.biaoti_two.setGeometry(QtCore.QRect(375, 75, 230, 40))
        self.biaoti_two.setStyleSheet("QPushButton{ font-family: 微软雅黑;" +
                                      "border: none; " +
                                      "color: #00;border-radius: 7px;" +
                                      "text-align: center;" +
                                      "text-decoration: none;" +
                                      "display: inline-block;" +
                                      "font-size: 19px;" + "cursor: pointer;}")
        self.biaoti_two.setText("手动输入")
        self.biaoti_two.clicked.connect(self.setup_ydhui)

        self.biaoti_three = QtWidgets.QPushButton(self)
        self.biaoti_three.setGeometry(QtCore.QRect(615, 75, 230, 40))
        self.biaoti_three.setStyleSheet("QPushButton{ font-family: 微软雅黑;" +
                                        "border: none; " +
                                        "color: #00;border-radius: 7px;" +
                                        "text-align: center;" +
                                        "text-decoration: none;" +
                                        "display: inline-block;" +
                                        "font-size: 19px;" +
                                        "cursor: pointer;}")
        self.biaoti_three.setText("随机生成")
        self.biaoti_three.clicked.connect(self.setup_yd)

        kuang_one = 370
        kuang_one_y = 150

        self.kuang = QLabel(self)
        self.kuang.setGeometry(QtCore.QRect(kuang_one, kuang_one_y, 480, 130))
        self.kuang.setStyleSheet("background-color: white;border-radius: 7px;")
        self.kuangshadow = QGraphicsDropShadowEffect(self)
        self.kuangshadow.setBlurRadius(30)
        cl = QColor("#eeeeee")
        self.kuangshadow.setColor(cl)
        self.kuangshadow.setOffset(0, 0)
        self.kuang.setGraphicsEffect(self.kuangshadow)

        self.edit = QtWidgets.QLineEdit(self)
        self.edit.setGeometry(
            QtCore.QRect(kuang_one + 20, kuang_one_y + 18, 440, 40))
        self.edit.textChanged.connect(self.set_yemian)
        self.edit.setPlaceholderText("访问页面 例如:1 2 3 4 5 6")
        self.edit.setStyleSheet(
            "QLineEdit{background-color: #f0f0f0;border-radius: 20px;border:0px solid #000;"
            "font-size: 18px;font-family: 微软雅黑;padding-left:16px;}")

        self.pushButton_18 = QtWidgets.QPushButton(self)
        self.pushButton_18.setGeometry(
            QtCore.QRect(kuang_one + 210, kuang_one_y + 18 + 40 + 15, 250, 40))
        self.pushButton_18.setStyleSheet(
            "QPushButton{background-color: #9dc3e6; font-family: 微软雅黑;" +
            "border: none;border: 0px solid #9dc3e6;" +
            "color: #fff;border-radius: 20px;" + "text-align: center;" +
            "text-decoration: none;padding-left:17px;" +
            "display: inline-block;" + "font-size: 18px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9ad0d0;color: white;"
            "}")
        self.pushButton_18.setText("执行")
        self.pushButton_18.clicked.connect(self.on_click_shou)
        self.kuang = QLabel(self)
        self.kuang.setGeometry(
            QtCore.QRect(kuang_one + 203, kuang_one_y + 18 + 40 + 14, 43, 43))
        self.kuang.setStyleSheet(
            "background-color: white;border-radius: 20px;border: 0px solid #000;"
        )

        self.edit2 = QtWidgets.QLineEdit(self)
        self.edit2.setGeometry(
            QtCore.QRect(kuang_one + 20, kuang_one_y + 18 + 40 + 15, 220, 40))
        self.edit2.textChanged.connect(self.set_kuaishu)
        self.edit2.setPlaceholderText("内存块数 > 0")
        self.edit2.setStyleSheet(
            "QLineEdit{background-color: #f0f0f0;border-radius: 20px;border:0px solid #f0f0f0;"
            "font-size: 18px;font-family: 微软雅黑;padding-left:16px;}")

        self.edit_suiji_num = QtWidgets.QLineEdit(self)
        self.edit_suiji_num.setGeometry(
            QtCore.QRect(kuang_one + 210, kuang_one_y + 18, 250, 40))
        self.edit_suiji_num.textChanged.connect(self.suiji_num)
        self.edit_suiji_num.setPlaceholderText("随机范围 例如:1 9")
        self.edit_suiji_num.setStyleSheet(
            "QLineEdit{background-color: #f0f0f0;border-radius: 20px;border:0px solid #000;"
            "font-size: 18px;font-family: 微软雅黑;padding-left:44px;}")

        self.yuan3 = QLabel(self)
        self.yuan3.setGeometry(
            QtCore.QRect(kuang_one + 203, kuang_one_y + 18, 43, 43))
        self.yuan3.setStyleSheet(
            "background-color: white;border-radius: 20px;border: 0px solid #000;"
        )
        self.edit_suiji_size = QtWidgets.QLineEdit(self)
        self.edit_suiji_size.setGeometry(
            QtCore.QRect(kuang_one + 20, kuang_one_y + 18, 220, 40))
        self.edit_suiji_size.textChanged.connect(self.set_suiji_size)
        self.edit_suiji_size.setPlaceholderText("随机数量 > 0")
        self.edit_suiji_size.setStyleSheet(
            "QLineEdit{background-color: #f0f0f0;border-radius: 20px;border:0px solid #000;"
            "font-size: 18px;font-family: 微软雅黑;padding-left:16px;}")

        self.pushButton_19 = QtWidgets.QPushButton(self)
        self.pushButton_19.setGeometry(
            QtCore.QRect(kuang_one + 210, kuang_one_y + 18 + 40 + 15, 250, 40))
        self.pushButton_19.setStyleSheet(
            "QPushButton{background-color: #9dc3e6; font-family: 微软雅黑;" +
            "border: none;border: 0px solid #9dc3e6;" +
            "color: #fff;border-radius: 20px;" + "text-align: center;" +
            "text-decoration: none;padding-left:17px;" +
            "display: inline-block;" + "font-size: 18px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9ad0d0;color: white;"
            "}")
        self.pushButton_19.setText("执行")
        self.pushButton_19.clicked.connect(self.on_click_suiji)

        self.yuan2 = QLabel(self)
        self.yuan2.setGeometry(
            QtCore.QRect(kuang_one + 203, kuang_one_y + 18 + 40 + 14, 43, 43))
        self.yuan2.setStyleSheet(
            "background-color: white;border-radius: 20px;border: 0px solid #000;"
        )
        self.edit22 = QtWidgets.QLineEdit(self)
        self.edit22.setGeometry(
            QtCore.QRect(kuang_one + 20, kuang_one_y + 18 + 40 + 15, 220, 40))
        self.edit22.textChanged.connect(self.set_neicunkuaishu)
        self.edit22.setPlaceholderText("内存块数 > 0")
        self.edit22.setStyleSheet(
            "QLineEdit{background-color: #f0f0f0;border-radius: 20px;border:0px solid #000;"
            "font-size: 18px;font-family: 微软雅黑;padding-left:16px;}")
        self.edit22.hide()
        self.yuan2.hide()
        self.pushButton_19.hide()
        self.edit_suiji_size.hide()
        self.yuan3.hide()
        self.edit_suiji_num.hide()
        self.grid = QGridLayout(self)
        self.grid.setGeometry(QtCore.QRect(500, 300, 330, 50))
        self.color = ["#e89291", "#c4b98b", "#81a8e1", "#8cc9c4", "#83bde2"]
        self.lab_list = []
        self.res = QLabel(self)
        self.res.setScaledContents(True)
        self.res.setStyleSheet(
            "background-color: #f0f0f0;border-radius: 7px;margin:4px;")
        self.res.adjustSize()
        self.scroll_area = QScrollArea(self)
        self.scroll_area.setWidget(self.res)
        self.scroll_area.setStyleSheet(
            "QScrollArea{background-color: #f0f0f0;border: 0px;border-radius: 7px;}"
            +
            "QScrollBar:horizontal {background-color: #bbd7ec;border: 0px;height: 14px;border-radius:7px;}"
            +
            "QScrollBar::handle:horizontal {background-color: #7fa6c8; height: 6px;border-radius:7px;}"
            +
            "QScrollBar::handle:horizontal:hover{background:#7fa6c8;height:6px;border-radius:7px;}"
            +
            "QScrollBar::handle:horizontal:pressed{background-color: #7fa6c8; height:6px;border-radius:7px;}"
            +
            "QScrollBar::add-page{background-color: #bbd7ec;border-radius:7px;}"
            +
            "QScrollBar::sub-page{background-color: #bbd7ec;border-radius:7px;}"
            + "QScrollBar::add-line:horizontal{width: 0px;}" +
            "QScrollBar::sub-line:horizontal{width: 0px;}" +
            "QScrollBar:vertical {background-color: #bbd7ec;border: 0px;width: 14px;border-radius:7px;}"
            +
            "QScrollBar::handle:vertical {background-color: #7fa6c8; width: 6px;border-radius:7px;}"
            +
            "QScrollBar::handle:vertical:hover{background:#7fa6c8;width:6px;border-radius:7px;}"
            +
            "QScrollBar::handle:vertical:pressed{background-color: #7fa6c8; width:6px;border-radius:7px;}"
            + "QScrollBar::add-line:vertical{heigth: 0px;border-radius:7px;}" +
            "QScrollBar::down-arrow:vertical{heigth: 0px;border-radius:7px;} "
            + "QScrollBar::up-arrow:vertical{heigth: 0px;border-radius:7px;}" +
            "QScrollBar::sub-line:vertical{heigth: 0px;border-radius:7px;}")
        self.v_layout = QVBoxLayout()
        self.v_layout.addWidget(self.scroll_area)
        # self.v_layout.addWidget(self.scrollbar)
        self.setLayout(self.v_layout)
        self.v_layout.setGeometry(QtCore.QRect(60, 320, 810, 310))
        self.error = QLabel(self)
        self.error.setGeometry(QtCore.QRect(470, 300, 330, 50))
        self.error.setStyleSheet(
            "text-align: center;background-color: #f44336;border-radius: 7px;border: 0px solid #000;color:#fff;font-size:18px;font-family: 微软雅黑;"
        )
        self.errorshadow = QGraphicsDropShadowEffect(self)
        self.errorshadow.setBlurRadius(30)
        cl = QColor("#cacaca")
        self.errorshadow.setColor(cl)
        self.errorshadow.setOffset(0, 0)
        self.error.setText("ERROR:数据不能为空 或 格式错误!!!")
        self.error.setGraphicsEffect(self.errorshadow)
        self.error.setAlignment(Qt.AlignCenter)
        self.error.hide()
        self.pushButton_img = QtWidgets.QPushButton(self)
        self.pushButton_img.setGeometry(
            QtCore.QRect(self.width() - 175,
                         self.height() - 160, 100, 107))
        self.pushButton_img.setStyleSheet(
            "QPushButton{border-image: url(:/data/mieba.png); font-family: 微软雅黑;"
            + "border: none;" + "color: #fff;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}" +
            "QPushButton:hover{border-image: url(:/data/ico.png)}")
        self.pushButton_img.clicked.connect(self.on_new_gui)

        self.pushButton_url = QtWidgets.QPushButton(self)
        self.pushButton_url.setGeometry(
            QtCore.QRect(self.width() - 330,
                         self.height() - 120, 100, 107))
        self.pushButton_url.setStyleSheet(
            "QPushButton{ font-family: 微软雅黑;" + "border: none;" +
            "color: #f7f7f7;border-radius: 7px;" + "text-align: center;" +
            "text-decoration: none;" + "display: inline-block;" +
            "font-size: 30px;" + "cursor: pointer;}")
        self.pushButton_url.setText("By Pc")
        self.pc_pl = 0
        self.pushButton_url.clicked.connect(self.go_to_url)

        self.queci = QLabel(self)
        self.queci.setGeometry(QtCore.QRect(915, 150, 290, 60))
        self.queci.setStyleSheet(
            "background-color: #f0f0f0;border-radius: 7px;")

        self.queci_text = QtWidgets.QPushButton(self)
        self.queci_text.setGeometry(QtCore.QRect(915, 150, 290, 60))
        self.queci_text.setStyleSheet("QPushButton{ font-family: 微软雅黑;" +
                                      "border: none; " +
                                      "color: #7a7a7a;border-radius: 5px;" +
                                      "text-align: center;" +
                                      "text-decoration: none;" +
                                      "display: inline-block;" +
                                      "font-size: 19px;" + "cursor: pointer;}")
        self.queci_text.setText("缺页次数")

        self.queci_one = QtWidgets.QPushButton(self)
        self.queci_one.setGeometry(QtCore.QRect(915, 220, 290, 60))
        self.queci_one.setStyleSheet(
            "QPushButton{background-color: white; font-family: 微软雅黑;" +
            "border: none; " + "color: #000;border-radius: 5px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")

        self.quelv = QLabel(self)
        self.quelv.setGeometry(QtCore.QRect(910, 320, 290, 60))
        self.quelv.setStyleSheet(
            "background-color: #f0f0f0;border-radius: 7px;")

        self.quelv_text = QtWidgets.QPushButton(self)
        self.quelv_text.setGeometry(QtCore.QRect(910, 322, 290, 60))
        self.quelv_text.setStyleSheet("QPushButton{ font-family: 微软雅黑;" +
                                      "border: none; " +
                                      "color: #7a7a7a;border-radius: 5px;" +
                                      "text-align: center;" +
                                      "text-decoration: none;" +
                                      "display: inline-block;" +
                                      "font-size: 19px;" + "cursor: pointer;}")
        self.quelv_text.setText("缺页率")

        self.quelv_one = QtWidgets.QPushButton(self)
        self.quelv_one.setGeometry(QtCore.QRect(910, 390, 290, 60))
        self.quelv_one.setStyleSheet(
            "QPushButton{background-color: white; font-family: 微软雅黑;" +
            "border: none; " + "color: #000;border-radius: 5px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")
        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

    def go_to_url(self):
        if self.pc_pl == 0:
            self.pushButton_url.setText("By Pl")
            self.pc_pl = 1
        elif self.pc_pl == 1:
            QtGui.QDesktopServices.openUrl(
                QtCore.QUrl('http://39.97.168.170/'))
            self.pc_pl = 2
        else:
            self.pushButton_url.setText("By Pc")
            self.pc_pl = 0

    def on_new_gui(self):
        self.ex = Example()
        self.ex.show()

    def suiji_num(self, text):
        self.suiji_num = text

    def set_suiji_size(self, text):
        self.suiji_size = text

    def set_neicunkuaishu(self, text):
        self.neicunkuaishu = text

    def setup_yd(self):
        if self.biaotipos == 1:
            self.biaotipos = 2
            self.kuang.hide()
            self.edit2.hide()
            self.pushButton_18.hide()
            self.edit.hide()
            self.edit22.show()
            self.yuan2.show()
            self.pushButton_19.show()
            self.edit_suiji_size.show()
            self.yuan3.show()
            self.edit_suiji_num.show()
            animation = QPropertyAnimation(self)
            animation.setTargetObject(self.biaoti_one)
            animation.setPropertyName(b"pos")
            animation.setStartValue(QPoint(375, 75))
            animation.setEndValue((QPoint(615, 75)))
            animation.setDuration(300)
            animation.start()

    def setup_ydhui(self):
        if self.biaotipos == 2:
            self.biaotipos = 1
            self.edit22.hide()
            self.yuan2.hide()
            self.pushButton_19.hide()
            self.edit_suiji_size.hide()
            self.yuan3.hide()
            self.edit_suiji_num.hide()
            self.kuang.show()
            self.edit2.show()
            self.pushButton_18.show()
            self.edit.show()
            animation = QPropertyAnimation(self)
            animation.setTargetObject(self.biaoti_one)
            animation.setPropertyName(b"pos")
            animation.setStartValue(QPoint(615, 75))
            animation.setEndValue((QPoint(375, 75)))
            animation.setDuration(300)

            animation.start()

    @pyqtSlot()
    def on_click(self):
        self.pushButton_15.setStyleSheet(
            "QPushButton{background-color: #7fa6c8; font-family: 微软雅黑;" +
            "border: none;" + "color: white;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")

        self.pushButton_16.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")

        self.pushButton_17.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")
        self.suanfa = 1

    @pyqtSlot()
    def on_click_two(self):

        self.pushButton_15.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")

        self.pushButton_16.setStyleSheet(
            "QPushButton{background-color: #7fa6c8; font-family: 微软雅黑;" +
            "border: none;" + "color: white;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")

        self.pushButton_17.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")
        self.suanfa = 2

    @pyqtSlot()
    def on_click_three(self):

        self.pushButton_15.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")

        self.pushButton_16.setStyleSheet(
            "QPushButton{background-color: #f0f0f0; font-family: 微软雅黑;" +
            "border: none; " + "color: #7a7a7a;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" + "cursor: pointer;}"
            "QPushButton:hover{ "
            "    background-color: #9dc3e6;color: white;"
            "}")

        self.pushButton_17.setStyleSheet(
            "QPushButton{background-color: #7fa6c8; font-family: 微软雅黑;" +
            "border: none;" + "color: white;border-radius: 7px;" +
            "text-align: center;" + "text-decoration: none;" +
            "display: inline-block;" + "font-size: 19px;" +
            "cursor: pointer;}")
        self.suanfa = 3

    @pyqtSlot()
    def setcilv(self, lv, ci):
        self.quelv_one.setText(str("%.4f%%" % (lv * 100)))
        self.queci_one.setText(str(ci) + "次")
        self.labelshadow = QGraphicsDropShadowEffect(self)
        self.labelshadow.setBlurRadius(15)
        cl = QColor("#cacaca")
        self.labelshadow.setColor(cl)
        self.labelshadow.setOffset(1, 1)
        self.queci_one.setGraphicsEffect(self.labelshadow)

        if lv > 0.75:
            self.queci_one.setStyleSheet(
                "QPushButton{background-color: #e89291; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
            self.quelv_one.setStyleSheet(
                "QPushButton{background-color: #e89291; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
        elif lv > 0.50:
            self.queci_one.setStyleSheet(
                "QPushButton{background-color: #f1916b; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
            self.quelv_one.setStyleSheet(
                "QPushButton{background-color: #f1916b; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
        elif lv > 0.25:
            self.queci_one.setStyleSheet(
                "QPushButton{background-color: #8cc9c4; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
            self.quelv_one.setStyleSheet(
                "QPushButton{background-color: #8cc9c4; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
        else:
            self.queci_one.setStyleSheet(
                "QPushButton{background-color:#83bde2; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
            self.quelv_one.setStyleSheet(
                "QPushButton{background-color: #83bde2; font-family: 微软雅黑;" +
                "border: none; " + "color: #fff;border-radius: 5px;" +
                "text-align: center;" + "text-decoration: none;" +
                "display: inline-block;" + "font-size: 19px;" +
                "cursor: pointer;}")
        self.labelshadow2 = QGraphicsDropShadowEffect(self)
        self.labelshadow2.setBlurRadius(15)
        cl = QColor("#cacaca")
        self.labelshadow2.setColor(cl)
        self.labelshadow2.setOffset(1, 1)
        self.quelv_one.setGraphicsEffect(self.labelshadow2)

    @pyqtSlot()
    def on_click_suiji(self):

        print("INF-suiji" + str(self.suanfa))

        # 范围
        try:
            if self.suanfa == 1:
                arr_fanwei = str.split(self.suiji_num)
                start = arr_fanwei[0]
                end = arr_fanwei[1]
                size = self.suiji_size
                shu = self.neicunkuaishu
                arr = []
                print(start)
                print(end)
                print(size)
                print(shu)
                for i in range(0, int(size)):
                    arr.append(random.randint(int(start), int(end)))
                print(arr)
                fifo = FIFO.main(arr, int(shu))
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                print("缺页次数===" + str(fifo.get_ci()))
                print("缺页率===" + str(fifo.get_lv()))
                self.setcilv(fifo.get_lv(), fifo.get_ci())
            elif self.suanfa == 2:
                arr_fanwei = str.split(self.suiji_num)
                start = arr_fanwei[0]
                end = arr_fanwei[1]
                size = self.suiji_size
                shu = self.neicunkuaishu
                arr = []
                print(start)
                print(end)
                print(size)
                print(shu)
                for i in range(0, int(size)):
                    arr.append(random.randint(int(start), int(end)))
                print(arr)
                fifo = LRU.main(arr, int(shu))
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                self.setcilv(fifo.get_lv(), fifo.get_ci())
            elif self.suanfa == 3:
                arr_fanwei = str.split(self.suiji_num)
                start = arr_fanwei[0]
                end = arr_fanwei[1]
                size = self.suiji_size
                shu = self.neicunkuaishu
                arr = []
                print(start)
                print(end)
                print(size)
                print(shu)
                for i in range(0, int(size)):
                    arr.append(random.randint(int(start), int(end)))
                print(arr)
                fifo = OPT.OPT(int(shu), arr)
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                self.setcilv(fifo.get_lv(), fifo.get_ci())
        except:
            traceback.print_exc()
            print("ERROR-kong")
            self.error.show()
            self.timer = QTimer()
            self.num = 0
            self.timer.timeout.connect(self.hideerror)
            self.timer.start(1500)

    @pyqtSlot()
    def on_click_shou(self):
        print("INF-self.suanfa=1")
        try:
            if self.suanfa == 1:
                print(self.kuaishu + self.yemian)
                arr_str = str.split(self.yemian)
                arr_int = [int(i) for i in arr_str]
                print(arr_int)
                print("INF==" + str(arr_int) + str(self.kuaishu))
                fifo = FIFO.main(arr_int, int(self.kuaishu))
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                self.setcilv(fifo.get_lv(), fifo.get_ci())

            elif self.suanfa == 2:

                print(self.kuaishu + self.yemian)
                arr_str = str.split(self.yemian)
                arr_int = [int(i) for i in arr_str]
                print(arr_int)
                print("INF==" + str(arr_int) + str(self.kuaishu))
                fifo = LRU.main(arr_int, int(self.kuaishu))
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                self.setcilv(fifo.get_lv(), fifo.get_ci())

            elif self.suanfa == 3:

                print(self.kuaishu + self.yemian)
                arr_str = str.split(self.yemian)
                arr_int = [int(i) for i in arr_str]
                print(arr_int)
                print("INF==" + str(arr_int) + str(self.kuaishu))
                fifo = OPT.OPT(int(self.kuaishu), arr_int)
                res = fifo.get_res()
                print(res)
                self.res.setText(res)
                self.res.adjustSize()
                self.setcilv(fifo.get_lv(), fifo.get_ci())
        except:
            print("ERROR-kong")
            self.error.show()
            self.timer = QTimer()
            self.num = 0
            self.timer.timeout.connect(self.hideerror)
            self.timer.start(1500)

    def hideerror(self):
        self.error.hide()

    def set_kuaishu(self, text):
        self.kuaishu = text

    def set_yemian(self, text):
        self.yemian = text

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate

    def mousePressEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.m_drag = True
            self.m_DragPosition = e.globalPos() - self.pos()
            e.accept()

    def mouseReleaseEvent(self, e):
        if e.button() == Qt.LeftButton:
            self.m_drag = False

    def mouseMoveEvent(self, e):
        try:
            if Qt.LeftButton and self.m_drag:
                self.move(e.globalPos() - self.m_DragPosition)
                e.accept()
        except:
            print("错误代码:000x0")
Esempio n. 11
0
class mainwind(QMainWindow, From_Main):
    def __init__(self):
        super(mainwind, self).__init__()
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.setGeometry(0, 0, 1350, 690)
        self.create_MenuBar()
        self.sc = pg.PlotWidget()
        self.sc2 = pg.PlotWidget()
        self.timer = QtCore.QTimer()
        # self.timer2 = QtCore.QTimer()
        self.init_UI()
        self.x = []
        self.x2 = []
        self.y = []
        self.y2 = []

        self.l = QVBoxLayout(self.graphicsView)
        self.l.setGeometry(QtCore.QRect(10, 5, 571, 150))
        self.l2 = QVBoxLayout(self.graphicsView_3)
        self.l2.setGeometry(QtCore.QRect(10, 440, 571, 150))

        self.l.addWidget(self.sc)
        self.l2.addWidget(self.sc2)

        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(660, 8, 600, 191))
        self.label.setText("")
        self.label.setStyleSheet("background-color: white")

        self.label2 = QLabel(self.centralwidget)
        self.label2.setGeometry(QtCore.QRect(660, 420, 600, 191))
        self.label2.setText("")
        self.label2.setStyleSheet("background-color: white")

    def init_UI(self):

        self.createpdf = QtWidgets.QPushButton(self.centralwidget)
        self.createpdf.setGeometry(QtCore.QRect(1270, 23, 75, 591))
        self.createpdf.setText(" Create PDF")
        self.createpdf.setObjectName("pdf")
        self.createpdf.setShortcut("Ctrl+F")
        self.createpdf.clicked.connect(lambda: self.savepdf())

        #  channel 1
        self.open3 = QtWidgets.QPushButton(self.centralwidget)
        self.open3.setGeometry(QtCore.QRect(20, 170, 41, 23))
        self.open3.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("images.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.open3.setIcon(icon1)
        self.open3.setObjectName("open")
        self.open3.setShortcut("Ctrl+O")
        self.open3.clicked.connect(lambda: self.OpenBrowse())

        self.play3 = QtWidgets.QPushButton(self.centralwidget)
        self.play3.setGeometry(QtCore.QRect(80, 170, 41, 23))
        self.play3.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("play.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.play3.setIcon(icon2)
        self.play3.setObjectName("play")
        self.play3.setShortcut("Ctrl+P")
        self.play3.clicked.connect(lambda: self.dynamicSig())

        self.pause3 = QtWidgets.QPushButton(self.centralwidget)
        self.pause3.setGeometry(QtCore.QRect(140, 170, 41, 23))
        self.pause3.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("pause.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.pause3.setIcon(icon3)
        self.pause3.setObjectName("pause")
        self.pause3.setShortcut("Ctrl+T")
        self.pause3.clicked.connect(lambda: self.pauseSignal())

        self.clear3 = QtWidgets.QPushButton(self.centralwidget)
        self.clear3.setGeometry(QtCore.QRect(200, 170, 41, 23))
        self.clear3.setText("")
        icon4 = QtGui.QIcon()
        icon4.addPixmap(QtGui.QPixmap("clear.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.clear3.setIcon(icon4)
        self.clear3.setObjectName("clear")
        self.clear3.setShortcut("Ctrl+L")
        self.clear3.clicked.connect(lambda: self.clear())

        self.zoom_in3 = QtWidgets.QPushButton(self.centralwidget)
        self.zoom_in3.setGeometry(QtCore.QRect(260, 170, 41, 23))
        self.zoom_in3.setText("")
        icon5 = QtGui.QIcon()
        icon5.addPixmap(QtGui.QPixmap("zoomin.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.zoom_in3.setIcon(icon5)
        self.zoom_in3.setObjectName("Zoom In")
        self.zoom_in3.setShortcut("Ctrl+Num++")
        self.zoom_in3.clicked.connect(lambda: self.zoomin())

        self.zoom_out3 = QtWidgets.QPushButton(self.centralwidget)
        self.zoom_out3.setGeometry(QtCore.QRect(320, 170, 41, 23))
        self.zoom_out3.setText("")
        icon6 = QtGui.QIcon()
        icon6.addPixmap(QtGui.QPixmap("zoomout.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.zoom_out3.setIcon(icon6)
        self.zoom_out3.setObjectName("Zoom Out")
        self.zoom_out3.setShortcut("Ctrl+-")
        self.zoom_out3.clicked.connect(lambda: self.zoomout())

        self.scroll_right3 = QtWidgets.QPushButton(self.centralwidget)
        self.scroll_right3.setGeometry(QtCore.QRect(380, 170, 41, 23))
        self.scroll_right3.setText("")
        icon7 = QtGui.QIcon()
        icon7.addPixmap(QtGui.QPixmap("arrowr.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.scroll_right3.setIcon(icon7)
        self.scroll_right3.setObjectName("scroll right")
        self.scroll_right3.setShortcut("Ctrl+Right")
        self.scroll_right3.clicked.connect(lambda: self.scrollR())

        self.scroll_left3 = QtWidgets.QPushButton(self.centralwidget)
        self.scroll_left3.setGeometry(QtCore.QRect(440, 170, 41, 23))
        self.scroll_left3.setText("")
        icon8 = QtGui.QIcon()
        icon8.addPixmap(QtGui.QPixmap("arrowl.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.scroll_left3.setIcon(icon8)
        self.scroll_left3.setObjectName("scroll left")
        self.scroll_left3.setShortcut("Ctrl+Left")
        self.scroll_left3.clicked.connect(lambda: self.scrollL())

        self.spectrogram3 = QtWidgets.QPushButton(self.centralwidget)
        self.spectrogram3.setGeometry(QtCore.QRect(500, 170, 41, 23))
        self.spectrogram3.setText("")
        icon9 = QtGui.QIcon()
        icon9.addPixmap(QtGui.QPixmap("spectro.png"), QtGui.QIcon.Normal,
                        QtGui.QIcon.Off)
        self.spectrogram3.setIcon(icon9)
        self.spectrogram3.setObjectName("spectrogram")
        self.spectrogram3.setShortcut("Ctrl+M")
        self.spectrogram3.clicked.connect(lambda: self.spectrogram())

        self.channel1box = QCheckBox("", self)
        self.channel1box.move(560, 190)
        self.channel1box.resize(16, 17)
        self.channel1box.setChecked(True)
        self.channel1box.setShortcut("Ctrl+H")
        self.channel1box.stateChanged.connect(self.show1)

        # channel 3
        self.channel3box = QCheckBox("", self)
        self.channel3box.move(560, 610)
        self.channel3box.resize(16, 17)
        self.channel3box.setChecked(True)
        self.channel3box.setShortcut("Alt+H")
        self.channel3box.stateChanged.connect(self.show3)

    def create_MenuBar(self):
        menuBar = self.menuBar()
        self.setMenuBar(menuBar)
        # self.menuBar.setShortcut("Alt")
        #        menubar file
        file_menu = menuBar.addMenu('file')

        open_action = QAction(QIcon("open.png"), "open File", self)
        file_menu.addAction(open_action)

        saveAction = QAction(QIcon("save.png"), "save", self)
        file_menu.addAction(saveAction)

        gdfAction = QAction("Export GDF...", self)
        file_menu.addAction(gdfAction)

        eventsAction = QAction("Export Events...", self)
        file_menu.addAction(eventsAction)

        importAction = QAction("Import Events...", self)
        file_menu.addAction(importAction)

        infoAction = QAction(QIcon("info.png"), "Info...", self)
        file_menu.addAction(infoAction)

        closeAction = QAction(QIcon("close.png"), "Close", self)
        file_menu.addAction(closeAction)
        closeAction.triggered.connect(self.close)
        closeAction.setShortcut("Ctrl+Q")

        # menubar  edit
        edit_menu = menuBar.addMenu('edit')

        undoAction = QAction(QIcon("undo.png"), "Undo", self)
        edit_menu.addAction(undoAction)

        redoAction = QAction(QIcon("redo.png"), "Redo", self)
        edit_menu.addAction(redoAction)

        toallAction = QAction(QIcon("to_all.png"), "to All Channels", self)
        edit_menu.addAction(toallAction)

        copyAction = QAction(QIcon("copy.png"), "Copy to Channels...", self)
        edit_menu.addAction(copyAction)

        deleteAction = QAction(QIcon("delete.png"), "Delete", self)
        edit_menu.addAction(deleteAction)

        changeAction = QAction(QIcon("change.png"), "Change Channel...", self)
        edit_menu.addAction(changeAction)

        typeAction = QAction(QIcon("color.png"), "Change Type", self)
        edit_menu.addAction(typeAction)

        insertAction = QAction(QIcon("add.png"), "Insert Over", self)
        edit_menu.addAction(insertAction)

        edit_menu.addAction('Quit', self.close)

        # menubar  mode
        mode_menu = menuBar.addMenu('mode')

        newAction = QAction(QIcon("new event.png"), "New Event", self)
        mode_menu.addAction(newAction)

        editAction = QAction(QIcon("edit.png"), "Edit Event", self)
        mode_menu.addAction(editAction)
        scrollAction = QAction(QIcon("scroll.png"), "Scroll", self)
        mode_menu.addAction(scrollAction)

        viewAction = QAction(QIcon("view.png"), "View Options", self)
        mode_menu.addAction(viewAction)

        # menubar  view
        view_menu = menuBar.addMenu('view')

        toolbarAction = QAction("Toolbars", self)
        view_menu.addAction(toolbarAction)

        statusAction = QAction("Statusbar", self)
        view_menu.addAction(statusAction)

        animationAction = QAction("Animation", self)
        view_menu.addAction(animationAction)

        eveAction = QAction(QIcon("favourite.png"), "Events...", self)
        view_menu.addAction(eveAction)

        channAction = QAction(QIcon("channels.png"), "Channels...", self)
        view_menu.addAction(channAction)

        scaleAction = QAction("Scale All", self)
        view_menu.addAction(scaleAction)

        zoominvAction = QAction(QIcon("zoomin.png"), "Zoom In Vertical", self)
        view_menu.addAction(zoominvAction)

        zoomoutvAction = QAction(QIcon("zoom out.png"), "Zoom Out Vertical",
                                 self)
        view_menu.addAction(zoomoutvAction)

        zoominhAction = QAction(QIcon("zoomin.png"), "Zoom In Horizontal",
                                self)
        view_menu.addAction(zoominhAction)

        zoomouthAction = QAction(QIcon("zoom out.png"), "Zoom Out Horizontal",
                                 self)
        view_menu.addAction(zoomouthAction)

        gotoAction = QAction(QIcon("goto.png"), "Go to...", self)
        view_menu.addAction(gotoAction)

        gonextAction = QAction("Goto and Select Next Event", self)
        view_menu.addAction(gonextAction)

        goprevAction = QAction("Goto and Select Previos Evenet", self)
        view_menu.addAction(goprevAction)

        fitAction = QAction("Fit View to selected Event", self)
        view_menu.addAction(fitAction)

        hideAction = QAction("Hide Events of Other Type", self)
        view_menu.addAction(hideAction)

        showAction = QAction("Show All Events", self)
        view_menu.addAction(showAction)

        # menubar  tools
        tools_menu = menuBar.addMenu('tools')

        calcAction = QAction("Calculate Mean...", self)
        tools_menu.addAction(calcAction)

        powerAction = QAction("Power Spectrum...", self)
        tools_menu.addAction(powerAction)

        # menubar  help
        help_menu = menuBar.addMenu('help')
        help_menu.addAction('Quit', self.close)

    ###CHANNEL 1 FUNCTIONS###

    def OpenBrowse(self):
        self.fileName, _ = QFileDialog.getOpenFileName(
            self, "QFileDialog.getOpenFileName()", "", "CSV Files (*.csv)")
        if self.fileName:
            df = pd.read_csv(self.fileName, header=None)
            self.x = np.array(df[0])
            self.y = np.array(df[1])
            xrange, yrange = self.sc.viewRange()
            self.min = self.x[0]
            self.max = self.x[-1]
            print(xrange, self.x[-1])

            self.sc.setXRange(xrange[0] / 5, xrange[1] / 5, padding=0)
            pen = pg.mkPen(color=(50, 50, 250))
            self.sc.plot(self.x, self.y, pen=pen)

    def scrollR(self):
        xrange, yrange = self.sc.viewRange()
        scrollvalue = (xrange[1] - xrange[0]) / 10
        if xrange[1] < self.max:
            self.sc.setXRange(xrange[0] + scrollvalue,
                              xrange[1] + scrollvalue,
                              padding=0)
            # self.sc.setYrange(yrange[0],yrange[1], padding=0)
        else:
            pass

    def scrollL(self):
        xrange, yrange = self.sc.viewRange()
        scrollvalue = (xrange[1] - xrange[0]) / 10
        if xrange[0] > self.min:
            self.sc.setXRange(xrange[0] - scrollvalue,
                              xrange[1] - scrollvalue,
                              padding=0)
        else:
            pass

    def zoomin(self):
        xrange, yrange = self.sc.viewRange()
        # self.sc.setYRange(yrange[0]/2, yrange[1]/2, padding=0)
        self.sc.setXRange(xrange[0] / 2, xrange[1] / 2, padding=0)

    def zoomout(self):
        xrange, yrange = self.sc.viewRange()
        # self.sc.setYRange(yrange[0]*2, yrange[1]*2, padding=0)
        self.sc.setXRange(xrange[0] * 2, xrange[1] * 2, padding=0)

    def clear(self):
        self.sc.clear()
        self.sc.setXRange(0, 1, padding=0)

    def dynamicSig(self):
        self.timer = QtCore.QTimer()
        self.timer.setInterval(5)
        self.timer.timeout.connect(self.dynamicSig)
        self.timer.start()
        xrange, yrange = self.sc.viewRange()
        scrollvalue = (xrange[1] - xrange[0]) / 500
        if xrange[1] < self.max:
            self.sc.setXRange(xrange[0] + scrollvalue,
                              xrange[1] + scrollvalue,
                              padding=0)
        else:
            pass

    def pauseSignal(self):
        self.timer.stop()

    def spectrogram(self):
        #plotting the spectrogram####
        # Define the list of frequencies
        self.frequencies = np.arange(5, 105, 5)

        # Sampling Frequency
        self.data = pd.DataFrame(pd.read_csv(self.fileName, delimiter=None))
        self.Data = self.data.iloc[1:][1:]
        self.sub2 = self.Data.values.tolist()
        self.samplingFrequency = 2 * (len(self.sub2)) + 1

        # Create two ndarrays
        self.s1 = np.empty([0])  # For samples
        self.s2 = np.empty([0])  # For signal

        # Start Value of the sample
        self.start = 1

        # Stop Value of the sample
        self.stop = self.samplingFrequency
        for self.frequency in self.frequencies:

            self.sub1 = np.arange(self.start, self.stop, 1)

        self.s1 = np.append(self.s1, self.sub1)
        self.s2 = np.append(self.s2, self.sub2)
        self.start = self.stop + 1
        self.stop = self.start + self.samplingFrequency

        # Plot the spectrogram
        fig = plot.figure()
        plot.subplot(111)
        self.powerSpectrum, self.freqenciesFound, self.time, self.imageAxis = plot.specgram(
            self.s2, Fs=self.samplingFrequency)
        plot.xlabel('Time')
        plot.ylabel('Frequency')
        fig.savefig('plot.png')
        self.upload()

    def upload(self):
        self.label.setPixmap(QtGui.QPixmap("plot.png"))
        self.label.setScaledContents(True)

    def show1(self):
        if (self.channel1box.isChecked() == True):
            self.graphicsView.show()
            self.label.show()
            self.open3.show()
            self.play3.show()
            self.pause3.show()
            self.clear3.show()
            self.zoom_in3.show()
            self.zoom_out3.show()
            self.scroll_right3.show()
            self.scroll_left3.show()
            self.spectrogram3.show()

        else:
            self.graphicsView.hide()
            self.label.hide()
            self.open3.hide()
            self.play3.hide()
            self.pause3.hide()
            self.clear3.hide()
            self.zoom_in3.hide()
            self.zoom_out3.hide()
            self.scroll_right3.hide()
            self.scroll_left3.hide()
            self.spectrogram3.hide()

    # channel 3
    def show3(self):
        if (self.channel3box.isChecked() == True):
            self.graphicsView_3.show()
            self.label2.show()
            # self.open2.show()
            # self.play2.show()
            # self.pause2.show()
            # self.clear_2.show()
            # self.zoom_in2.show()
            # self.zoom_out2.show()
            # self.scroll_right2.show()
            # self.scroll_left2.show()
            # self.spectrogram_2.show()

        else:
            self.graphicsView_3.hide()
            self.label2.hide()
            # self.open2.hide()
            # self.play2.hide()
            # self.pause2.hide()
            # self.clear_2.hide()
            # self.zoom_in2.hide()
            # self.zoom_out2.hide()
            # self.scroll_right2.hide()
            # self.scroll_left2.hide()
            # self.spectrogram_2.hide()

    ##save to pdf function##

    def savepdf(self):
        fig = plot.figure()

        if (self.channel1box.isChecked() == True):
            if len(self.x) == 0:
                pass
            else:
                plot.subplot(3, 2, 1)
                plot.plot(self.x,
                          self.y,
                          color='red',
                          linewidth=2,
                          scalex=True)
                plot.subplot(3, 2, 2)
                self.powerSpectrum, self.freqenciesFound, self.time, self.imageAxis = plot.specgram(
                    self.s2, Fs=self.samplingFrequency)
                plot.xlabel('Time')
                plot.ylabel('Frequency')
                # if(self.channel2box.isChecked()==True):
                #     if len(self.x1) ==0 :
                #         pass
                #     else:
                #         plot.subplot(3,2,3)
                #         plot.plot(self.x1,self.y1,color='red',linewidth=2,scalex=True)
                #         plot.subplot(3,2,4)
                #         self.powerSpectrum1, self.freqenciesFound1, self.time1, self.imageAxis1 = plot.specgram(self.s2, Fs=self.samplingFrequency)
                #         plot.xlabel('Time')
                plot.ylabel('Frequency')
        if (self.channel3box.isChecked() == True):
            if len(self.x2) == 0:
                pass
            else:
                plot.subplot(3, 2, 5)
                plot.plot(self.x2,
                          self.y2,
                          color='red',
                          linewidth=2,
                          scalex=True)
                plot.subplot(3, 2, 6)
                self.powerSpectrum2, self.freqenciesFound2, self.time2, self.imageAxis2 = plot.specgram(
                    self.s2, Fs=self.samplingFrequency)
                plot.xlabel('Time')
                plot.ylabel('Frequency')
        # plot.show()
        fig.savefig("x.pdf")
Esempio n. 12
0
class toolWindow(QMainWindow):

    def __init__(self,parent = None):
        super(toolWindow,self).__init__(parent)
        self.socketStatus = 0#定义socket连接的状态 0 未连接,不占资源 1 连接中 占用资源 2 连接成功
        self.setupUi()

    #工具界面设置
    def setupUi(self):
        self.setWindowTitle("DspDebugTool")
        self.resize(1200,675)
        #菜单栏设置
        self.file = self.menuBar().addMenu("文件")# 在menuBar上添加文件菜单
        self.openVariable = QAction("打开 (Ctrl+O)", self)
        self.saveVariable = QAction("保存 (Ctrl+S)", self)
        self.exitTool = QAction("退出", self)
        
        #为一个Action设置快捷键
        self.openVariable.setShortcut('Ctrl+O')
        self.saveVariable.setShortcut('Ctrl+S')
        
        #绑定动作控件
        self.file.addAction(self.openVariable)
        self.file.addAction(self.saveVariable)
        self.file.addAction(self.exitTool)

        # 为文件-->保存绑定槽函数
        self.openVariable.triggered.connect(self.openProcess)
        self.saveVariable.triggered.connect(self.saveProcess)
        self.exitTool.triggered.connect(self.exitDspTool)
        
        #添加 关于 的菜单栏
        self.about = self.menuBar().addMenu("关于")
        self.toolInfo = QAction("软件信息", self)
        self.authorInfo = QAction("作者信息", self)
        self.about.addAction(self.toolInfo)
        self.about.addAction(self.authorInfo)
        self.toolInfo.triggered.connect(self.showTool)
        self.authorInfo.triggered.connect(self.showAuthor)

        #实例化控件时可以指定父控件QWidget(self),指定当前类为父控件,也可以不用指定父控件
        self.toolWidget = QWidget()
        self.setCentralWidget(self.toolWidget) #绑定中心控件
        self.widgetLayout = QVBoxLayout()#创建垂直布局
        self.widgetLayout.setGeometry(QRect(0,0,1200,675))
        self.widgetLayout.setObjectName("widgetLayout")
        self.toolWidget.setLayout(self.widgetLayout)#设置中心布局为垂直布局
        
        #创建一系列控件用于设置信息
        self.portMessageSetLayout = QHBoxLayout()#添加水平分布的格子,用于放置端口信息设置
        self.ipBoxHint = QLabel('服务器地址:')
        self.ipBox = QLineEdit('10.10.100.254')
        self.PortHint = QLabel('服务器端口:')
        self.Port = QLineEdit('8899')
        self.Port.setValidator(QIntValidator(0, 65535))
        self.desAddressHint = QLabel('目的地址:')
        self.desAddress = QLineEdit('100')
        self.desAddress.setValidator(QIntValidator(0,254))
        self.connectBox = QPushButton('连接服务器')

        #将控件添加到布局中
        self.portMessageSetLayout.addWidget(self.ipBoxHint)
        self.portMessageSetLayout.addWidget(self.ipBox)
        self.portMessageSetLayout.addWidget(self.PortHint)
        self.portMessageSetLayout.addWidget(self.Port)
        self.portMessageSetLayout.addWidget(self.desAddressHint)
        self.portMessageSetLayout.addWidget(self.desAddress)
        self.portMessageSetLayout.addWidget(self.connectBox)
        self.widgetLayout.addLayout(self.portMessageSetLayout)
        #绑定控件操作
        self.connectBox.clicked.connect(self.connectServer)
        self.desAddress.returnPressed.connect(self.setDesAddress)
        #创建发送变量区
        self.gridLayout_1 = QGridLayout()#创建网格布局
        self.gridLayout_1.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_1.setObjectName("gridLayout_1")
        self.sendList= []
        
        for i in range(15):
            self.sendList.append(SendWidget(self.sendMessageBySocket,self,i))
            self.gridLayout_1.addWidget(self.sendList[i],i//5,i%5)
        self.widgetLayout.addLayout(self.gridLayout_1)
        #创建接收变量显示区
        self.gridLayout_2 = QGridLayout()
        self.gridLayout_2.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.RecieverList= []
        for i in range(12):
            self.RecieverList.append(RecieverWidget(self,i))
            self.gridLayout_2.addWidget(self.RecieverList[i],i//6,i%6)
        self.widgetLayout.addLayout(self.gridLayout_2)
        
        #设置状态栏
        self.socketStatusBar = QLabel('socket等待连接...')
        self.txStatus = QLabel('等待启动发送线程...')
        self.rxStatus = QLabel('等待启动接收线程...')
        self.statusBar().addPermanentWidget(self.socketStatusBar,stretch=2)
        self.statusBar().addPermanentWidget(self.txStatus,stretch=2)
        self.statusBar().addPermanentWidget(self.rxStatus,stretch=2)
        
    def sendMessageBySocket(self,widgetNum,VariableName,VariableValue):
        print('发送信号的插件是:'+str(widgetNum))
        print('发送'+VariableName+'的值为:'+VariableValue)
        self.txStatusShowMessage('插件'+str(widgetNum)+'发送的值为:'+VariableValue)
        
        if not VariableValue == '':#判断数据非空则进行发送
            if self.socketStatus == 2:#判断是否连接上soket
                #通过socket发送数据,首先设置功能码为6
                if self.txThread.setFunctionCode(6):
                    #成功设置功能码则发送的数据,包括寄存器的地址和寄存器
                    self.txThread.sendData([widgetNum,float(VariableValue)])
            else:
                self.showMessageBox('未连接到服务器\n先点击连接服务器')
                pass

    #设置下位机通信地址
    def setDesAddress(self):
        self.txThread.setDestinationAddress(int(self.desAddress.text()))
        self.rxThread.setDestinationAddress(int(self.desAddress.text()))
    
    #新建线程执行耗时任务,避免阻塞界面进程
    def connectServer(self):
        #若socket已连接则需要完全关闭才能重新连接
        if self.socketStatus == 0:
            print('开始连接')
            #新建线程执行链接任务
            self.tcpClientSocket = socket.socket()
            self.conThread = connectThread(self.ipBox.text(),int(self.Port.text()),self.tcpClientSocket)
            self.conThread.connectSignal.connect(self.socketLinkProcess)
            self.conThread.start()
            self.socketStatusBar.setText('socket连接中...')
            self.socketStatus = 1
        
        elif self.socketStatus == 2:
            print('已经打开了socket连接,先关闭再连接到新链接')
            try:
                #释放掉已经连接占用的资源
                self.tcpClientSocket.shutdown(2)
                self.tcpClientSocket.close()
                self.txThread.terminateThread()
                self.rxThread.terminateThread()
                #重新连接
                self.tcpClientSocket = socket.socket()
                self.conThread = connectThread(self.ipBox.text(),int(self.Port.text()),self.tcpClientSocket)
                self.conThread.connectSignal.connect(self.socketLinkProcess)
                self.conThread.start()
                self.socketStatus = 1
                self.socketStatusBar.setText('socket连接中...')
                pass
            except socket.error as e:
                print(e)
                self.showMessageBox('连接服务器时发生错误!\n'+str(e))
                pass
            pass
        
    
    def socketLinkProcess(self,msg):
        if msg =='链接成功!!':
            #启动线程执行发送任务
            self.txThread = TransmitMessageThread(self.tcpClientSocket)#新建一个线程用于发送数据
            self.txThread.statusSignal.connect(self.txStatusShowMessage)
            self.txThread.setDestinationAddress(int(self.desAddress.text()))
            self.txThread.start()#
            self.txStatusShowMessage('发送线程启动')
            
            #启动线程执行接收任务
            self.rxThread = ReceiveMessageThread(self.tcpClientSocket)#新建一个线程用于接收数据
            self.rxThread.statusSignal.connect(self.rxStatusShowMessage)
            self.rxThread.resultSignal.connect(self.receiveData)
            self.rxThread.setDestinationAddress(int(self.desAddress.text()))
            self.rxThread.start()#
            self.rxStatusShowMessage('接收线程启动')
            self.showMessageBox('连接成功!\n已经启动通信线程')
            #socket通信线程启动成功
            self.socketStatus = 2
            self.socketStatusBar.setText('socket连接成功')
        else:
            self.socketStatus = 0 #连接错误时已经释放掉socket资源
            self.showMessageBox(msg)
            pass


    #从DSP接收到数据。并通过界面显示数据
    def receiveData(self):

        if self.rxThread.destinationAddress == 254:
            if self.rxThread.functionCode == 4:
                data = self.rxThread.readData()
                print(data)
                if not data ==[]:
                    for i in range(len(data)-1):
                        self.RecieverList[data[0]+i].label.setText(str(data[i+1]))
                pass
            if self.rxThread.functionCode == 7:
                self.txStatusShowMessage('发送写指令已收到!!!')
                print(self.rxThread.data)
                pass
        self.rxThread.finishedFlag = True
    
    #通过messageBox弹窗警告
    def showMessageBox(self,msg):    
        QMessageBox(QMessageBox.Warning,'警告',msg).exec_()
    
    #展示发送线程的状态
    def txStatusShowMessage(self,msg):
        self.txStatus.setText('发送线程状态:'+msg)
    
    #展示接收线程的状态
    def rxStatusShowMessage(self,msg):
        self.rxStatus.setText('接收线程状态:'+msg)
    
    #保存界面上的内容
    def saveProcess(self):
        with open('info.txt','w',encoding='utf-8') as fileInfo:
            for _ in self.sendList:
                data = [_.lineEditName.text(),_.lineEditValue.text()]
                fileInfo.write(str(data)+'\n')
            fileInfo.flush()
        fileInfo.close()
        self.showMessageBox('保存成功')

    #将界面上保存的内容,导回界面
    def openProcess(self):
        try:
            with open('info.txt','r',encoding='utf-8') as fileInfo:
                for i in range(len(self.sendList)) :
                    info = fileInfo.readline().split(', ')
                    if not info[0] == '[\'\'' :
                        self.sendList[i].lineEditName.setText(info[0][2:-1])
                    if not info[1] == '\'\']\n':
                        self.sendList[i].lineEditValue.setText(info[1][1:-3])
                fileInfo.close
            self.showMessageBox('打开成功')
            pass
        except FileNotFoundError as e:
            print(e)
            self.showMessageBox('文件不存在')
            pass    
    
    #展示软件信息
    def showTool(self):
        msg = 'DSP通信工具 V0.1\n图形库 PyQt5-5.15'
        QMessageBox(QMessageBox.Warning,'信息',msg).exec_()
    
    #展示软件作者信息
    def showAuthor(self):
        msg = 'Created By yujie1315\n2020年11月11日'
        QMessageBox(QMessageBox.Warning,'信息',msg).exec_()

    #退出软件
    def exitDspTool(self):
        print('退出软件')
        self.rxThread.terminateThread()
        self.txThread.terminateThread()
        self.close()
Esempio n. 13
0
class Table(QMainWindow):

    def __init__(self, player_index):
        super().__init__()
        self.initUI(0, player_index)

    def initUI(self, p, player_index):
        self.answer = None
        self.moves_made = 0
        self.boxes = []
        self.checkboxes = []
        self.presses = 0
        self.last_throws = (0, 0)
        self.figures = []
        self.player_color = QColor(255, 255, 0)
        self.player_starting_pos = player_index * 14
        self.current_move = 0
        self.player_cnt = 0

        self.command_widget = QVBoxLayout()
        self.roll_dice_button = QPushButton('Roll dice', self)
        self.roll_dice_button.clicked.connect(self._roll_dice)
        self.command_widget.addWidget(self.roll_dice_button)
        self.command_widget.setGeometry(QRect(650, 300, 200, 100))

        # outer parts
        for i in range(0, 7):
            self.__build_square(self.boxes, i, 335, 545 -
                                (i % 15) * 35, QColor(255, 255, 255))
        for i in range(7, 13):
            self.__build_square(self.boxes, i, 370 + (i - 7)
                                * 35, 335, QColor(255, 255, 255))
        self.__build_square(self.boxes, 13, 545, 300, QColor(255, 255, 255))

        for i in range(14, 20):
            self.__build_square(self.boxes, i, 265 + (22 - i)
                                * 35, 265, QColor(255, 255, 255))
        for i in range(20, 27):
            self.__build_square(self.boxes, i, 335, 265 -
                                (i - 20) * 35, QColor(255, 255, 255))
        self.__build_square(self.boxes, 27, 300, 55, QColor(255, 255, 255))

        for i in range(28, 35):
            self.__build_square(self.boxes, i, 265, 55 +
                                (i - 28) * 35, QColor(255, 255, 255))
        for i in range(35, 41):
            self.__build_square(self.boxes, i, 230 - (i - 35)
                                * 35, 265, QColor(255, 255, 255))
        self.__build_square(self.boxes, 41, 55, 300, QColor(255, 255, 255))

        for i in range(42, 49):
            self.__build_square(self.boxes, i, 55 + (i - 42)
                                * 35, 335, QColor(255, 255, 255))
        for i in range(49, 55):
            self.__build_square(self.boxes, i, 265, 370 +
                                (i - 49) * 35, QColor(255, 255, 255))
        self.__build_square(self.boxes, 55, 300, 545, QColor(255, 255, 255))

        # inner parts
        for i in range(56, 62):
            self.__build_square(self.boxes, i, 300, 510 -
                                (i - 56) * 35, QColor(200, 0, 0))
        for i in range(62, 68):
            self.__build_square(self.boxes, i, 510 - (i - 62)
                                * 35, 300, QColor(0, 0, 200))
        for i in range(68, 74):
            self.__build_square(self.boxes, i, 300, 90 +
                                (i - 68) * 35, QColor(200, 0, 200))
        for i in range(74, 80):
            self.__build_square(self.boxes, i, 90 + (i - 74)
                                * 35, 300, QColor(p, 200, 200))

        self.setGeometry(600, 900, 900, 600)
        self.show()

# Table builder function
    def __add_checkbox(self, index):
        box = QVBoxLayout()
        checkbox = QCheckBox(str(index), self)
        self.checkboxes.append(checkbox)
        checkbox.stateChanged.connect(self.signal_for_figure)
        checkbox.setCheckable(False)
        box.addWidget(checkbox)
        self.boxes[index].setLayout(box)

    def __build_square(self, boxes, i, horiz, vert, color):
        self.boxes.append(QFrame(self))
        self.boxes[i].setGeometry(horiz, vert, 30, 30)
        self.boxes[i].setStyleSheet(
            "QWidget {background-color: %s }" %
            color.name())


# Figure behaviour functions
    def draw_figure(self, figure_pos, player_color, counter):
        self.boxes[figure_pos].setStyleSheet(
            "QWidget {background-color: %s }" %
            QColor(
                player_color[0],
                player_color[1],
                player_color[2]).name())
        # self.lbl[figure_pos].setText(str(counter))

    def __move_figure(self, old_figure_pos, new_figure_pos):
        #self.__draw_figure(old_figure_pos, (255,255,255))
        #result = function_for_movement()
        # returns tuple like (old_cnt, new_pos, new_cnt)
        old_cnt = 0
        old_pos = old_figure_pos
        new_pos = new_figure_pos
        new_cnt = 1

        if old_cnt:
            self.draw_figure(old_pos, (255, 255, 255), old_cnt)
        else:
            self.draw_figure(old_pos, (255, 255, 255), 0)
        self.draw_figure(new_pos, (255, 255, 0), new_cnt)

    def __get_checked_pos(self):
        i = 0
        for checkbox in self.checkboxes:
            if checkbox.isChecked():
                return i
            i += 1

    def signal_for_figure(self):
        # move figure
        old_pos = self.__get_checked_pos()
        self.__move_figure(old_pos, self.current_move)
#######################################
# Dice behaviour functions

    def _roll_dice(self):
        # roll dice
        # server side
        res = testing_event_function()
        self.last_throws = (res['first_dice'], res['second_dice'])
        # checks if a new figure can be used
        if res['can_get_new_figure']:
            for elem in [throw for throw in self.last_throws if throw == 6]:
                self.roll_dice_button.setEnabled(False)
                self.new_window = Popup(self)
            # print(help(self.new_window))
                # backend for choosing the right figure
        return


############################################

    def _get_new_figure(self):
        # backend gets new figure
        # frontend shows new figure
        pass
Esempio n. 14
0
    def home(self):

        #Quit Button Right
        quitbtn = QPushButton("Quit", self)
        quitbtn.clicked.connect(self.close_app)
        quitbtn.setStatusTip("Quit Program")
        quitbtn.resize(quitbtn.sizeHint())
        quitbtn.setStyleSheet(
            "background-color: red;border-radius: 15px; "
            "border-color: orange;padding: 20px;"
            " border-top: 10px transparent;border-bottom:"
            " 10px transparent;border-right: 10px transparent;border-left: 10px transparent;"
        )
        #quitbtn.move(100, 100)

        #Select Image
        loadimgbtn = QPushButton("Load image", self)
        loadimgbtn.clicked.connect(self.load_image)
        loadimgbtn.setStatusTip("Browse for image")
        loadimgbtn.resize(loadimgbtn.sizeHint())
        loadimgbtn.setStyleSheet(
            "background-color: cyan;border-radius: 15px; border-color: orange;padding: 20px; border-top: 10px transparent;border-bottom: 10px transparent;border-right: 10px transparent;border-left: 10px transparent;"
        )
        #quitbtn.move(100, 100)

        #Extract Image
        extracttxtbtn = QPushButton("Extract text", self)

        extracttxtbtn.setStatusTip("Extract image from text")
        extracttxtbtn.resize(extracttxtbtn.sizeHint())
        extracttxtbtn.setEnabled(True)
        extracttxtbtn.clicked.connect(self.emitSignal)
        #extracttxtbtn.clicked.connect(onClick)
        self.upload_complete_signal.connect(
            lambda: extracttxtbtn.setEnabled(True))
        QtCore.QCoreApplication.processEvents()
        extracttxtbtn.clicked.connect(self.extract_text)
        extracttxtbtn.setStyleSheet(
            "background-color: Blue;border-radius: 15px; border-color: orange;padding: 20px; border-top: 10px transparent;border-bottom: 10px transparent;border-right: 10px transparent;border-left: 10px transparent;"
        )

        #quitbtn.move(100, 100)
        #Play Text
        cropimgbtn = QPushButton("Play Text", self)
        cropimgbtn.clicked.connect(self.playText)
        cropimgbtn.setStatusTip("Play audio output")
        cropimgbtn.setEnabled(True)
        self.extract_complete_signal.connect(
            lambda: cropimgbtn.setEnabled(True))

        cropimgbtn.resize(cropimgbtn.sizeHint())
        cropimgbtn.setStyleSheet(
            "background-color: orange;border-radius: 15px; border-color: orange;padding: 20px; border-top: 10px transparent;border-bottom: 10px transparent;border-right: 10px transparent;border-left: 10px transparent;"
        )
        #quitbtn.move(100, 100)

        #File location QLabel
        loc_qlabel = QLabel(self)
        loc_qlabel.hide()
        [
            self.loc_qlabel_signal.connect(x) for x in [
                lambda: loc_qlabel.setText(self.location_name),
                lambda: loc_qlabel.show()
            ]
        ]
        loc_qlabel.move(925, 150)
        self.loc_qlabel_signal.connect(lambda: loc_qlabel.show())
        loc_qlabel.setStyleSheet("QLabel {  color : white; }")

        #Crop boundary QLabel
        img_bound_qlabel = QLabel(self)
        img_bound_qlabel.hide()
        myString = ",".join(str(v) for v in self.boundary_xy)
        [
            self.extract_start_signal.connect(x) for x in [
                lambda: img_bound_qlabel.setText("Extracting..."),
                lambda: img_bound_qlabel.show()
            ]
        ]
        img_bound_qlabel.move(925, 248)
        img_bound_qlabel.setStyleSheet("QLabel { color : white; }")
        [
            self.extract_complete_signal.connect(x) for x in [
                lambda: img_bound_qlabel.setText("Done"),
                lambda: img_bound_qlabel.show()
            ]
        ]

        #Vertical Box Right
        v_but_box = QVBoxLayout()
        v_but_box.addWidget(loadimgbtn)
        v_but_box.addWidget(extracttxtbtn)
        v_but_box.addWidget(cropimgbtn)
        v_but_box.addWidget(quitbtn)

        v_but_box.setGeometry(QtCore.QRect(900, 46, 150, 450))

        #Insert OCR image
        pic = QLabel(self)
        #pic.setGeometry(200, 22, 800, 100)
        #use full ABSOLUTE path to the image, not relative
        #pic.setPixmap(QtGui.QPixmap("nn2.png"))

        self.show()