def __init__(self, parent=None): # 主窗口界面 super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setFixedSize(800, 600) self.difficulty = 3 # 难度 self.setWindowTitle('小学算术题 难度:%d' % self.difficulty) self.setWindowIcon(QIcon('res/image/windowIcon.jpg')) self.ui.pauseBtn.setIcon(QIcon('res/image/pause.png')) # 设置窗口界面 self.setting = Setting() self.setting._close_signal.connect(self.on_setting_closed) # 音效加载 self.playlist = QMediaPlaylist() self.playlist.addMedia(QMediaContent(QUrl('res/audio/correct.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/wrong.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/complete.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/timeOver.mp3'))) self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.play() # 定义变量 self.answer = 0 self.total = 0 self.correct = 0 self.accuracy = 0. self.overtime = 0 self.tmpOutput = [] # 保存路径 self.fpath = 'history.txt' # 定时器初始化 self.timeLimit = 30 self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.currentTime = self.timeLimit self.ui.timeLabel.setText(str(self.currentTime)) self.pause = False # 错题模式初始化 self.mistakeBatchSize = 5 self.mistakeMode = False self.exitingMistakeMode = False self.ui.tipLabel.clear() self.ui.remainingLabel.clear() self.questionQueue = [] # 第一次开始运行 self.refreshQuestion() self.refreshBoard() # 计时器开始计时 self.timer.start(1000)
def __init__(self): self.image = None self.path = "" self.app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.__setup()
def __init__(self): self.app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.pathQueue = [] self.__setup() self.init_frm()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.lyricsWindow = LyricsWindow(mainWindow=self) self.chordsWindow = ChordsWindow(mainWindow=self) self.confirmDialog = ConfirmDialog(mainWindow=self) self.loginDialog = LoginDialog(mainWindow=self) self.registerDialog = RegisterDialog(mainWindow=self) setupUi.mainWindow(self)
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # Define DB instance self.DB = sqlite3DB("DB/weatherStation.db") # Define properties self.is_connected = False self.is_configured = False self.dev = None self.status = "checking" self.USBString = "" # Define main ui self.window = Ui_MainWindow() self.window.setupUi(self) # Set log textBrowser as read only self.window.textBrowser.setReadOnly(True) self.window.textBrowser.setCursorWidth(0) # Generate compass widget self.compass = compassWidget() self.window.compassLayout.addWidget(self.compass) # Restore last time window geometry self.settings = QSettings('JMDMahdi', 'WeatherStation') geometry = self.settings.value('geometry', '') if isinstance(geometry, QByteArray): self.restoreGeometry(geometry) # Update the home tab with last received data self.updateHomeTab() # Define chart tab charts and add them to view self.generateCharts() # Set default statusbar text self.window.statusbar.showMessage('Checking ...') # Build background thread for USB self.threadpool = QThreadPool() # Pass the function to execute in background self.worker = Worker(self.USB_process) self.worker.signals.progress.connect(self.processData) self.worker.signals.statusbar.connect(self.updateStatusBar) # Execute self.threadpool.start(self.worker)
class MainWindow(QMainWindow): allSongs = [] currentSong = None allCurrentChords = [] currentChordsIndex = -1 def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.lyricsWindow = LyricsWindow(mainWindow=self) self.chordsWindow = ChordsWindow(mainWindow=self) self.confirmDialog = ConfirmDialog(mainWindow=self) self.loginDialog = LoginDialog(mainWindow=self) self.registerDialog = RegisterDialog(mainWindow=self) setupUi.mainWindow(self) def showAlert(self, text, title='Alert!'): self.alertBox = AlertBox(text, title) self.alertBox.show()
def __init__(self): """ Setting up the GUI. """ super(ImageDialog, self).__init__() # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.Console.append("-------------------------------") self.ui.Console.append("RosConnect Console") self.ui.Console.append("-------------------------------") # Create globle variable for cw global cw cw = self.ui.centralwidget # Remember to pass the definition/method, not the return value! # Load the config.yaml file to the Config window self.loadConfiguration() # Show mouse over self.showHelp() # Connect the buttons self.ui.StartCarBttn.clicked.connect(self.startCarBttnAction) self.ui.runSimBttn.clicked.connect(self.startSimBttnAction) self.ui.stopCarBttn.clicked.connect(self.emergencyBttnAction) # self.ui.treeView.clicked.connect(self.populateEditor) # Connect the menu options self.ui.actionLoad_Profile.triggered.connect( lambda: self.loadProfile()) self.ui.actionSave_Profile.triggered.connect( lambda: self.saveProfile()) self.ui.menuClear_Config.triggered.connect(lambda: self.clearProfile())
class MainWindowController(object): def __init__(self): self.image = None self.path = "" self.app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.__setup() def __setup(self): # Files self.ui.actionOpen.triggered.connect(self.onTriggerd_actionOpen) self.ui.actionReload_Image.triggered.connect(self.reloadImage) self.ui.actionSave.triggered.connect(self.onTriggerd_actionSave) self.ui.actionExit.triggered.connect(self.trigger_actionExit) # Colorspace self.ui.actionRGB.triggered.connect(self.RGB) self.ui.actionHSV.triggered.connect(self.HSV) self.ui.actionGrayscale.triggered.connect(self.Grayscale) # Transformations self.ui.actionFlip_Horizontal.triggered.connect(self.flipH) self.ui.actionFlip_Vertical.triggered.connect(self.flipV) self.ui.actionRotateClockwise.triggered.connect(self.rotateC) self.ui.actionRotateAntiClockwise.triggered.connect(self.rotateA) # Morphological Transformations self.ui.actionErosion.triggered.connect(self.erosion) self.ui.actionDilation.triggered.connect(self.dilation) self.ui.actionOpening.triggered.connect(self.opening) self.ui.actionClosing.triggered.connect(self.closing) self.ui.actionMorphological_Gradient.triggered.connect(self.morphologicalGradient) def reloadImage(self): if self.path and len(self.path) > 0: isImage = imghdr.what(self.path) if isImage is not None: self.image = cv2.imread(self.path,cv2.IMREAD_UNCHANGED) if self.image is None: print("Error to reload image") else: print("Reloaded") self.updateImage() def onTriggerd_actionOpen(self): dialog = QtWidgets.QFileDialog() dialog.setFileMode(QtWidgets.QFileDialog.FileMode()) file = dialog.getOpenFileName(None,'Open an image') if file and len(file[0]) > 0: self.path = file[0] isImage = imghdr.what(self.path) if isImage is not None: self.image = cv2.imread(self.path,cv2.IMREAD_UNCHANGED) if self.image is None: print("Error") else: self.updateImage() else: print("isn't an image") else: print("Open a file") def onTriggerd_actionSave(self): if self.image is not None: dialog = QtWidgets.QFileDialog() dialog.setFileMode(QtWidgets.QFileDialog.FileMode()) file = dialog.getSaveFileName(None,'Save an image') if file and len(file[0]) > 0: cv2.imwrite(file[0] +".png",self.image) else: print("Open an image") def trigger_actionExit(self): sys.exit() def updateImage(self): size = self.image.shape step = self.image.size / size[0] if len(size) == 3: if size[2] == 4: qformat = QImage.Format_RGBA8888 else: qformat = QImage.Format_RGB888 else: qformat = QImage.Format_Indexed8 img = QImage(self.image, size[1], size[0], step, qformat) img = img.rgbSwapped() pixMap = QPixmap.fromImage(img) self.ui.lbImage.setPixmap(pixMap) #Show colorspace def RGB(self): if self.image is not None: b = self.image.copy() b[:,:,0],b[:,:,1],b[:,:,2] = b[:,:,0],0,0 g = self.image.copy() g[:,:,0],g[:,:,1],g[:,:,2] = 0,g[:,:,1],0 r = self.image.copy() r[:,:,0],r[:,:,1],r[:,:,2] = 0,0,r[:,:,2] cv2.imshow('R',r) cv2.imshow('G',g) cv2.imshow('B',b) def HSV(self): if self.image is not None: hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV) cv2.imshow('HUE',hsv[:,:,0]) cv2.imshow('SAT',hsv[:,:,1]) cv2.imshow('VAL',hsv[:,:,2]) def Grayscale(self): if self.image is not None: gs = cv2.cvtColor(self.image,cv2.COLOR_BGR2GRAY) cv2.imshow('Grayscale',gs) def flipH(self): if self.image is not None: self.image = cv2.flip(self.image,0) self.updateImage() def flipV(self): if self.image is not None: self.image = cv2.flip(self.image,1) self.updateImage() def rotateA(self): self.rotate_scale(-5,1) def rotateC(self): self.rotate_scale(5,1) def rotate_scale(self,angle,scale): r,c,_ = self.image.shape mat = cv2.getRotationMatrix2D((r/2,c/2),angle,scale) self.image = cv2.warpAffine(self.image,mat,(c,r)) def erosion (self): self.morphologicalTrasformation(0) def dilation(self): self.morphologicalTrasformation(1) def opening(self): self.morphologicalTrasformation(2) def closing(self): self.morphologicalTrasformation(3) def morphologicalGradient(self): self.morphologicalTrasformation(4) def morphologicalTrasformation(self,oper): if self.image is not None: kernel = np.ones((5,5),np.uint8) if oper == 0: self.image = cv2.erode(self.image,kernel,iterations = 1) elif oper == 1: self.image = cv2.dilate(self.image,kernel,iterations = 1) elif oper == 2: self.image = cv2.morphologyEx(self.image, cv2.MORPH_OPEN, kernel) elif oper == 3: self.image =cv2.morphologyEx(self.image, cv2.MORPH_CLOSE, kernel) elif oper == 4: self.image =cv2.morphologyEx(self.image, cv2.MORPH_GRADIENT, kernel) self.updateImage()
class MyUi(QMainWindow): def __init__(self, parent=None): # 主窗口界面 super().__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setFixedSize(800, 600) self.difficulty = 3 # 难度 self.setWindowTitle('小学算术题 难度:%d' % self.difficulty) self.setWindowIcon(QIcon('res/image/windowIcon.jpg')) self.ui.pauseBtn.setIcon(QIcon('res/image/pause.png')) # 设置窗口界面 self.setting = Setting() self.setting._close_signal.connect(self.on_setting_closed) # 音效加载 self.playlist = QMediaPlaylist() self.playlist.addMedia(QMediaContent(QUrl('res/audio/correct.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/wrong.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/complete.mp3'))) self.playlist.addMedia(QMediaContent(QUrl('res/audio/timeOver.mp3'))) self.playlist.setPlaybackMode(QMediaPlaylist.CurrentItemOnce) self.player = QMediaPlayer() self.player.setPlaylist(self.playlist) self.player.play() # 定义变量 self.answer = 0 self.total = 0 self.correct = 0 self.accuracy = 0. self.overtime = 0 self.tmpOutput = [] # 保存路径 self.fpath = 'history.txt' # 定时器初始化 self.timeLimit = 30 self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.currentTime = self.timeLimit self.ui.timeLabel.setText(str(self.currentTime)) self.pause = False # 错题模式初始化 self.mistakeBatchSize = 5 self.mistakeMode = False self.exitingMistakeMode = False self.ui.tipLabel.clear() self.ui.remainingLabel.clear() self.questionQueue = [] # 第一次开始运行 self.refreshQuestion() self.refreshBoard() # 计时器开始计时 self.timer.start(1000) # 刷新题目 def refreshQuestion(self): # 清空self.tmpOutput以防刷新问题后将上一题也写入文件 self.tmpOutput.clear() # 非错题模式随机出题 if self.questionQueue == []: assert self.mistakeMode == False a = random.randint(0, 10 ** self.difficulty) b = random.randint(0, 10 ** self.difficulty) symbol, self.answer = (' + ', a + b) if random.random() > 0.5 else (' - ', a - b) # 错题模式从self.questionQueue中出题 else: assert self.mistakeMode == True self.ui.remainingLabel.setText('剩余:{}/{}'.format(len(self.questionQueue), self.mistakeBatchSize)) a, symbol, b = self.questionQueue.pop(0) self.answer = eval(a + symbol + b) self.tmpOutput.append('(*)') # 判断是否是最后一道错题 if self.questionQueue == []: self.exitingMistakeMode = True # 将题目放入self.tmpOutput中等待写入文件 self.tmpOutput.append('Question: ' + '{} {} {}:'.format(a, symbol, b)) self.ui.questionLabel.setText(str(a) + symbol + str(b)) self.ui.judgeLabel.setText('') self.ui.lineEdit.setFocus() # 更新记录板显示 def refreshBoard(self): self.ui.correctLabel.setText('答对:%d/%d' % (self.correct, self.total)) self.ui.accuracyLabel.setText('准确率:{:.0%}'.format(self.accuracy)) self.ui.overtimeLabel.setText('超时次数:{}'.format(self.overtime)) # 更新计时器时间 def refreshTime(self): self.ui.timeLabel.setText(str(self.timeLimit)) self.currentTime = self.timeLimit # 将self.tmpOutput中的字符串写入文件 def writeFile(self): with open(self.fpath, 'a') as f: f.write('\t'.join(self.tmpOutput) + '\n') self.tmpOutput.clear() @pyqtSlot() def on_answerBtn_clicked(self): self.ui.lineEdit.setText(str(self.answer)) @pyqtSlot() def on_refreshBtn_clicked(self): self.refreshQuestion() self.refreshTime() @pyqtSlot() def on_submitBtn_clicked(self): userInput = self.ui.lineEdit.text().strip() self.ui.lineEdit.clear() # 判断输入是否合法 if re.match('^-?\d+$', userInput): # 若回答正确 if eval(userInput) == self.answer: # 播放0号音效 self.player.stop() self.playlist.setCurrentIndex(0) self.player.play() # UI响应 self.ui.judgeLabel.setText('回答正确!') # 记录板更新变量,写入文件 self.correct += 1 self.total += 1 self.accuracy = round(self.correct / self.total, 2) self.tmpOutput.append(userInput) self.writeFile() # 如果这是最后一个错题的话,有些地方要特殊处理 if self.exitingMistakeMode == True: # 修改状态 self.exitingMistakeMode = False self.mistakeMode = False # 播放2号音效 self.playlist.setCurrentIndex(2) self.player.play() # UI响应 self.ui.tipLabel.setText('完成错题模式!') self.ui.remainingLabel.clear() # 更新问题,记录板显示,计时器时间 self.refreshBoard() self.refreshQuestion() self.refreshTime() # 若回答错误 else: # # 播放1号音效 # self.player.stop() # self.playlist.setCurrentIndex(1) # self.player.play() # UI响应 self.ui.judgeLabel.setText('回答错误!再思考一下!') # 记录板更新变量,不写入文件 self.total += 1 self.accuracy = round(self.correct / self.total, 2) self.tmpOutput.append('*' + userInput) # 更新记录板显示,计时器时间,不刷新问题 self.refreshBoard() self.refreshTime() @pyqtSlot() def on_timer_timeout(self): self.currentTime -= 1 # 若还有剩余时间 if self.currentTime > 0: self.ui.timeLabel.setText(str(self.currentTime)) # 若超时 else: assert self.currentTime == 0 # 播放3号音效 self.player.stop() self.playlist.setCurrentIndex(3) self.player.play() # UI响应 QMessageBox.information(self, '1', '超时了!') self.overtime += 1 self.refreshTime() self.refreshBoard() @pyqtSlot() def on_pauseBtn_clicked(self): # 暂停 if not self.pause: self.timer.stop() self.ui.pauseBtn.setIcon(QIcon('res/image/start.jpg')) self.pause = True # 取消暂停 else: self.timer.start(1000) self.ui.pauseBtn.setIcon(QIcon('res/image/pause.png')) self.pause = False @pyqtSlot() def on_historyBtn_clicked(self): # 暂停 if not self.pause: self.timer.stop() self.ui.pauseBtn.setIcon(QIcon('res/image/start.jpg')) self.pause = True # TODO 也许以后可以用QTableWidget美化输出 # with open(self.fpath,'r') as f: # content = f.read() # 用打开记事本的方法看历史记录 os.system(self.fpath) @pyqtSlot() def on_mistakeModeBtn_clicked(self): # 开启错题模式 self.mistakeMode = True # 更新计时器时间 self.currentTime = self.timeLimit self.ui.timeLabel.setText(str(self.currentTime)) # 读取历史记录中的错题(读取数不超过self.mistakeBatchSize个),并将其赋值给self.mistakeQueue with open(self.fpath, 'r') as f: lines = f.readlines() mistakeList = [] for Question in lines: if '*' in Question: questionText = Question.split(':')[1].strip() assert len(questionText.split()) == 3 mistakeList.append(questionText.split()) if len(mistakeList) == self.mistakeBatchSize: break assert len(mistakeList) <= self.mistakeBatchSize random.shuffle(mistakeList) # 随机打乱这些错题 self.questionQueue = mistakeList # UI响应 self.ui.tipLabel.setText('正在重做错题模式') self.ui.lineEdit.clear() # 刷新问题 self.refreshQuestion() @pyqtSlot() def on_settingBtn_clicked(self): # 暂停 if not self.pause: self.timer.stop() self.ui.pauseBtn.setIcon(QIcon('res/image/start.jpg')) self.pause = True self.setting.show() @pyqtSlot() def on_setting_closed(self): # 将设置值赋予主窗口 self.difficulty, self.timeLimit, self.mistakeBatchSize = \ self.setting.difficultyValue, self.setting.timeLimitValue, self.setting.mistakeBatchSizeValue
class ImageDialog(QtWidgets.QMainWindow): def __init__(self): """ Setting up the GUI. """ super(ImageDialog, self).__init__() # Set up the user interface from Designer. self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.Console.append("-------------------------------") self.ui.Console.append("RosConnect Console") self.ui.Console.append("-------------------------------") # Create globle variable for cw global cw cw = self.ui.centralwidget # Remember to pass the definition/method, not the return value! # Load the config.yaml file to the Config window self.loadConfiguration() # Show mouse over self.showHelp() # Connect the buttons self.ui.StartCarBttn.clicked.connect(self.startCarBttnAction) self.ui.runSimBttn.clicked.connect(self.startSimBttnAction) self.ui.stopCarBttn.clicked.connect(self.emergencyBttnAction) # self.ui.treeView.clicked.connect(self.populateEditor) # Connect the menu options self.ui.actionLoad_Profile.triggered.connect( lambda: self.loadProfile()) self.ui.actionSave_Profile.triggered.connect( lambda: self.saveProfile()) self.ui.menuClear_Config.triggered.connect(lambda: self.clearProfile()) def loadConfiguration(self): """ Takes in a configuration file as a yaml, and parses the information to populate the GUI with the configurations options. """ # this is where the configuration file will be read in # and radio buttons renamed with open('config.yaml') as file: modules = yaml.load(file, Loader=yaml.FullLoader) iteration = 0 for module in modules.items(): if (iteration == 0): # iteration zero is our version number global versionNum versionNum = module[1] elif (iteration == 1): # first group added to row 0 col 0 # makes a group for the current module self.group = QtWidgets.QGroupBox(self.ui.centralwidget) # sets the objects name to be the name module self.group.setObjectName(module[1]["variable"]) self.ui.gridLayout.addWidget(self.group, 0, 0, 1, 3) variables.append(module[1]["variable"]) else: # makes a group for the current module self.group = QtWidgets.QGroupBox(self.ui.centralwidget) # sets the objects name to be the name module self.group.setObjectName(module[1]["variable"]) self.ui.gridLayout.addWidget(self.group, 1, \ iteration-2, 1, 1) # all other groups added to row 1 and then the next open col self.ui.gridLayout.addWidget(self.group, 1, iteration - 2) variables.append(module[1]["variable"]) if (iteration >= 1): self.group.setTitle(module[0]) # sets the title in the UI # each group gets its own form layout where bttns are added self.formLayout = QtWidgets.QFormLayout(self.group) self.formLayout.setObjectName("formLayout_" + module[0]) configGroups.append(list()) # makes array for the grouping for choice in module[1]["choices"].items(): self.group.setToolTip(module[1]["description"]) radioBttns.append(choice[0]) # button array # add buttons to their respective groups configGroups[iteration - 1].append(choice[0]) # create the button in the GUI self.bttn = QtWidgets.QRadioButton(self.group) # this is the name we use to access the object self.bttn.setObjectName(choice[0]) # the text seen in the GUI self.bttn.setText(choice[1]["title"]) # get this buttons dependency list mydep = choice[1]["dependencies"] # save the dependency list from yaml to global variable dependencies[choice[0]] = mydep # add the button to the layout self.formLayout.addWidget(self.bttn) # Set the tool tip/mouse over for help. desc = choice[1]["description"] self.bttn.setToolTip(desc) # connect onclicked function to the button self.bttn.clicked.connect(partial(\ self.saveSelectedOptions,choice[0], iteration-1)) self.bttn.clicked.connect(partial(\ self.setDependencies,choice[0], mydep)) #for each of the racing stratagies determine which sim to run if (iteration == 1): simScripts.append(choice[1]["sim"]) iteration += 1 # load any previously saved options in the klepto file savedData.txt self.loadPreviousOptions() def saveSelectedOptions(self, name, moduleNum): """ When the user selects all of the buttons they want to, they can save that option to use later on if they end up changing it. Parameters ---------- name This is the name of the button that was selected. moduleNum This is where the button is stored in the GUI. """ arch = file_archive('savedData.txt', serialized=True) mapp = arch.archive arch["Version"] = versionNum # this radio buttons group group = configGroups[moduleNum] # find our radio button object for choice in group: if choice == name: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) break # if the button is checked, then add it to the savedData.txt file if radio_button.isChecked(): arch[variables[moduleNum]] = name arch.dump() else: # otherwise remove the button from savedData.txt mapp.pop(variables[moduleNum]) def setDependencies(self, this_radbttn, dependencies): sz = len(configGroups) for item in range(0, sz): # loop over all groups group = configGroups[item] if dependencies != None: # do we have a depenedencies list? for choice in group: if (choice != this_radbttn) and (choice not in dependencies): radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setEnabled(False) radio_button.setAutoExclusive(False) if radio_button.isChecked(): radio_button.toggle() else: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setAutoExclusive(False) else: # otherwise, assume we have no dependencies for this button for choice in group: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setAutoExclusive(False) # determine if all the buttons are un-clicked enable_all = True for checked in range(0, sz): # loop over all groups group = configGroups[checked] for choice in group: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) if radio_button.isChecked(): enable_all = False # if so, then undo all disabling if enable_all: for undo in range(0, sz): # loop over all groups group = configGroups[undo] for choice in group: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setEnabled(True) def showHelp(self): """ This method hows helpful information to the user when you mouse over anything on our GUI. """ self.ui.StartCarBttn.setToolTip( 'Select the configuration you want then\ press start car to start the car.') self.ui.runSimBttn.setToolTip( 'Select the configuration you want. Press\ run sim to see how the car will perform in a simulation.') self.ui.stopCarBttn.setToolTip('Press Stop car and have a script sent\ to the car to stop it.') self.ui.Console.setToolTip('This is where we will show important\ information to the user.') self.ui.menubar.setToolTip('Inside the file you will see a load and\ save profile option.') self.ui.menuFile.setToolTip('The load profile takes in a saved profile\ and loads it into the GUI.\nThe save profile will take current\ selected configurations and save them to a file.') self.ui.actionLoad_Profile.setToolTip('This is where you can select a\ profile to load into the GUI.') self.ui.actionLoad_Profile.setToolTip('This is where you can save the\ selected configuration to a window.') def loadData(self, dictionary, from_savedData): """ This function lets the user load in any profile saved. There is a check to make sure that you can only load in valid profiles. Parameters ---------- dictionary This what is the dictionary that is passed in that is holding all of the information. from_savedData This is a boolean value that will tell if it loading in from a saved value or just the previous profile. """ # Print where we are loading data from. if (from_savedData): self.ui.Console.append("> ...") self.ui.Console.append("> Loading previous session") else: self.ui.Console.append("> ...") self.ui.Console.append("> Loading profile") # Check to see if dictionary is empty # Depending on where we are loading from gives a different message. if len(dictionary) == 0: if from_savedData: self.ui.Console.append("> WARNING: saved session not found.") self.ui.Console.append("> The config window will be") self.ui.Console.append("> left blank.") return else: self.ui.Console.append("> WARNING: profile is blank.") return # Check to see if version numbers match if "Version:" in dictionary: if dictionary["Version"] != str(versionNum): if from_savedData: self.ui.Console.append( "> WARNING: Config Version Mismatch. Could not load previous session." ) else: print("Inside comparison of version numbers") self.ui.Console.append( "> WARNING: Config Version Mismatch. Could not load profile." ) # Check to see if we are loading from a file. if (not from_savedData): # - Clear the config window of any settings sz = len(configGroups) # - enabled all buttons # - un toggle all buttons that are currently toggled for item in range(0, sz): for choice in configGroups[item]: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setEnabled(True) if radio_button.isChecked(): radio_button.toggle() # Load data into the GUI iteration = 0 for data in dictionary: if iteration != 0: var = cw.findChild(QtWidgets.QRadioButton, dictionary[data]) if var is not None: var.toggle() else: self.ui.Console.append( "> You are not able to toggle a radio button that doesn't exist." ) iteration += 1 # make sure to disable any buttons not in this dependency tree sz = len(configGroups) for undo in range(0, sz): for choice in configGroups[undo]: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) if (radio_button.isChecked()): self.setDependencies(choice, dependencies[choice]) if from_savedData: self.ui.Console.append( "> Previous session successfully loaded.") else: self.ui.Console.append( "> Your selected profile has been successfully loaded" ) return def loadPreviousOptions(self): """ Loads the previous option from the klepto saved file. """ arch = file_archive('savedData.txt') dictionary = arch.archive self.loadData(dictionary, True) def generateLaunchVars(self): """ Return the launch string to use properly in the launch file. """ arch = file_archive('savedData.txt') dictionary = arch.archive param = "" for item in dictionary: if item == 'Version': continue test = item + ":=" + dictionary[item] param += test + " " return param def startCarBttnAction(self): """ Holds the logic for when the user wants to start the car. """ # define global bool value for use at closure of application global CAR_RUNNING self.ui.Console.append("> ...") self.ui.Console.append("> Starting car") self.ui.Console.append("> This may take some time") params = self.generateLaunchVars() command = 'cd Scripts; ./runSSH.sh "$1"' CAR_RUNNING = subprocess.Popen([command, 'sh',params], \ shell=True, preexec_fn=os.setsid) if CAR_RUNNING.returncode == None: self.ui.Console.append("> Vehicle has been loaded successfully") else: self.ui.Console.append("> Error: Vehicle has *not* been loaded") def startSimBttnAction(self): """ Holds the logic for when the user wants to start the simulation of the car. """ self.ui.Console.append("> ...") self.ui.Console.append("> Loading simulator") global SIM_RUNNING arch = file_archive('savedData.txt') dictionary = arch.archive stradegyVar = variables[0] #the first variable is our racing stradegy choiceVar = dictionary[stradegyVar] #the currently selected choice simIndex = configGroups[0].index( choiceVar ) #the index of our choice var corresponds to our sim Index #run sim SIM_RUNNING = subprocess.Popen(['cd Scripts; screen -dmS sim ./' \ + str(simScripts[simIndex]) + ' &'], shell=True, preexec_fn=os.setsid) #output to console if SIM_RUNNING.returncode == None: self.ui.Console.append("> Simulator has been loaded successfully") else: self.ui.Console.append("> Error: simulator has *not* been loaded") def emergencyBttnAction(self): """ Holds the logic to stop the car if the user presses stop Car button. """ # This is executed when the button is pressed self.ui.Console.append("> ...") self.ui.Console.append("> Stopping car") self.ui.Console.append("> This may take some time") subprocess.call(['cd Scripts; ./carStop_test.sh'], shell=True) def loadProfile(self): """ loads a saved profile that the user would like to see back in the GUI. """ dictionary = {} dialog = QFileDialog() fname = dialog.getOpenFileName(None, ("Select File"), ".txt") arch = file_archive('savedData.txt') disk = arch.archive # clear the disk archive for key in disk: if "Version" not in key: disk.pop(key) # print(disk) with open(fname[0]) as file: for index in file: (key, val) = index.split() key = key[:len(key) - 1] if val in radioBttns or key == "Version": dictionary[key] = val else: self.ui.Console.append( "> The value for {} is not part of the current config file" .format(key)) arch[key] = val arch.dump() self.loadData(dictionary, False) def saveProfile(self): """ Holds the logic to save all of the selected configuration options into a profile. """ self.ui.Console.append("> ...") self.ui.Console.append("> Saving profile") name = QFileDialog.getSaveFileName(self, 'Save File') f = open(name[0], 'w') arch = file_archive('savedData.txt') dictionary = arch.archive for item in dictionary: f.write("%s: %s\n" % (item, dictionary[item])) f.close() self.ui.Console.append("> Your profile has been saved sucessfully.") def clearProfile(self): self.ui.Console.append("> Clearing Profile...") # - Clear the config window of any settings sz = len(configGroups) # - enabled all buttons # - un toggle all buttons that are currently toggled for undo in range(0, sz): for choice in configGroups[undo]: radio_button = cw.findChild(QtWidgets.QRadioButton, choice) radio_button.setEnabled(True) if radio_button.isChecked(): radio_button.toggle() @atexit.register def closeROS(): """ This function is used when the user closes out of GUI, this method will make sure Robot Operating System and Screen will close. """ nodes = os.popen("rosnode list").readlines() for item in range(len(nodes)): nodes[item] = nodes[item].replace("\n", "") for node in nodes: os.system("rosnode kill " + node) if ('SIM_RUNNING' in globals()): os.system("screen -S sim -X quit") if ('CAR_RUNNING' in globals()): subprocess.call(['cd Scripts; ./closeScreen.sh'], shell=True)
def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self)
class mywindow(QtWidgets.QMainWindow): def __init__(self): super(mywindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self)
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # Define DB instance self.DB = sqlite3DB("DB/weatherStation.db") # Define properties self.is_connected = False self.is_configured = False self.dev = None self.status = "checking" self.USBString = "" # Define main ui self.window = Ui_MainWindow() self.window.setupUi(self) # Set log textBrowser as read only self.window.textBrowser.setReadOnly(True) self.window.textBrowser.setCursorWidth(0) # Generate compass widget self.compass = compassWidget() self.window.compassLayout.addWidget(self.compass) # Restore last time window geometry self.settings = QSettings('JMDMahdi', 'WeatherStation') geometry = self.settings.value('geometry', '') if isinstance(geometry, QByteArray): self.restoreGeometry(geometry) # Update the home tab with last received data self.updateHomeTab() # Define chart tab charts and add them to view self.generateCharts() # Set default statusbar text self.window.statusbar.showMessage('Checking ...') # Build background thread for USB self.threadpool = QThreadPool() # Pass the function to execute in background self.worker = Worker(self.USB_process) self.worker.signals.progress.connect(self.processData) self.worker.signals.statusbar.connect(self.updateStatusBar) # Execute self.threadpool.start(self.worker) def processData(self, data): # Remove completed data indicators from string and pass into insertData function, to insert to db self.insertData(data) def USB_process(self, process_callback, UIUpdateCallBack): global _CloseApp # Check device status continuously while True: if _CloseApp: # End thread on close signal # Close UI QApplication.quit() return if self.is_connected: # Wait for data from device try: # Get USB data and pass to main thread to process data = self.dev.read(0x81, 32, 2000) # Convert data to uint8 array dataBytes = np.array(data.tolist(), dtype=np.uint8) # Convert data to float list process_callback.emit( dataBytes.view(dtype=np.float32).tolist()) except Exception as e: if not ("Operation timed out" in str(e) or "Pipe error" in str(e) or "Input/Output Error" in str(e) or "No such device" in str(e)): print("self.dev.read error: " + str(e)) # Recheck device status self.check_if_device_connected(UIUpdateCallBack, True) time.sleep(1) pass else: # Recheck device status every 1 secound if device not connected time.sleep(1) UIUpdateCallBack.emit(self.is_connected) self.check_if_device_connected(UIUpdateCallBack, True) def device_connected(self): # Set device status on UI as connected if self.status != "connected": self.writeLog("Device connected\n") self.window.statusbar.showMessage('Connected') self.window.statusbar.setStyleSheet('color: green') self.status = "connected" def device_disconnected(self): # Set device status on UI as disconnected if self.status != "disconnected": self.writeLog("Device disconnected\n") self.window.statusbar.showMessage('Disconnected') self.window.statusbar.setStyleSheet('color: red') self.status = "disconnected" def updateStatusBar(self, status): if status: self.device_connected() else: self.device_disconnected() def find_device(self): # Search connected device for our device and return device descriptor dev_g = usb.core.find(backend=backend, idVendor=5511, idProduct=63322, find_all=True) dev_list = list(dev_g) if dev_list is None: return None try: dev = dev_list[0] except: try: dev = dev_list.next() except: return None return dev def check_if_device_connected(self, UIUpdateCallBack, force=False): # Search for our device self.dev = self.find_device() if self.dev is None: self.is_connected = False self.is_configured = False else: self.is_connected = True # Gain access to read the device if not done already if force or not self.is_configured: # This must be done on every connection self.config_device() # Set status on UI UIUpdateCallBack.emit(self.is_connected) def config_device(self): # Gain access to device try: self.dev.reset() except: self.is_configured = False return pass try: self.dev.set_configuration() except usb.core.USBError: pass cfg = self.dev.get_active_configuration() intf = usb.util.find_descriptor(cfg, bInterfaceNumber=1) if not intf: raise ("Interface not found") if platform.system() != "Windows": if self.dev.is_kernel_driver_active(intf.bInterfaceNumber) is True: self.dev.detach_kernel_driver(intf.bInterfaceNumber) self.is_configured = True def closeEvent(self, event): global _CloseApp # Confirm close reply = QMessageBox.question( self, 'Window Close', 'Are you sure you want to close the window?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: # Save window geometry to restore next time self.settings.setValue('geometry', self.saveGeometry()) # Tell worker to stop processing _CloseApp = True # Wait for the worker to end self.threadpool.waitForDone() # Close app event.accept() else: event.ignore() def updateHomeTab(self): '''Update the home tab with last received data''' # Get last data lastData = self.DB.getLastRow() # Fill lastData with 0 if data not available if lastData is None: lastData = (0, 0, 0, 0, 0, 0, 0) # Convert timestamp to datetime date = datetime.fromtimestamp((lastData[6])) # Update home tab with last data self.window.temperatureText.setText(str(lastData[0]) + " °C") self.window.pressureText.setText(str(lastData[1] / 100) + " hPa") self.window.lightIntensityText.setText(str(lastData[2]) + " lux") self.window.humidityText.setText(str(lastData[3]) + " %") self.window.windSpeedText.setText(str(lastData[4]) + " m/s") self.compass.setAngle(int(lastData[5])) self.window.windAngleText.setText(str(lastData[5]) + " °") if platform.system() != "Windows": self.window.dateText.setText(date.strftime("%A, %-d %B %Y")) else: self.window.dateText.setText(date.strftime("%A, %e %B %Y")) self.window.timeText.setText(date.strftime("%I:%M %p")) def insertData(self, data): self.writeLog("Received data: " + " ,".join(map(str, data)) + " | Status: ") if len(data) == 8: self.DB.insert(data) self.writeLog("Successfully inserted to db\n", False) self.updateHomeTab() else: self.writeLog("Invalid data\n", False) def writeLog(self, text, insertTime=True): self.window.textBrowser.moveCursor(QTextCursor.End) if insertTime: self.window.textBrowser.insertPlainText( datetime.now().strftime("%a %b %d %H:%M:%S.%f %Y") + "> ") self.window.textBrowser.insertPlainText(text) if self.window.checkBox.isChecked(): self.window.textBrowser.verticalScrollBar().setValue( self.window.textBrowser.verticalScrollBar().maximum()) def generateCharts(self): # Add chart widgets self.temperatureChart = chartWidget(None, "Temperature records in celcius", "Time", "Temperature") self.window.chartTabContents.addWidget(self.temperatureChart) self.pressureChart = chartWidget(None, "Pressure records in Pa", "Time", "Pressure") self.window.chartTabContents.addWidget(self.pressureChart) self.LightIntensityChart = chartWidget( None, "Light intensity records in lux", "Time", "Light intensity") self.window.chartTabContents.addWidget(self.LightIntensityChart) self.humidityChart = chartWidget(None, "Humidity records in percent", "Time", "Humidity") self.window.chartTabContents.addWidget(self.humidityChart) self.windSpeedChart = chartWidget(None, "Wind speed records in m/s", "Time", "Wind speed") self.window.chartTabContents.addWidget(self.windSpeedChart) # Update dateEdits date today = datetime.now() week_ago = today - timedelta(days=7) self.window.firstDate.setDate(week_ago.date()) self.window.secondDate.setDate(today.date()) # Call updateCharts on date changes self.window.firstDate.dateChanged.connect(self.updateCharts) self.window.secondDate.dateChanged.connect(self.updateCharts) # Update charts series from db self.updateCharts() def updateCharts(self): # Get dates secondDate = self.window.secondDate.date().toPyDate() firstDate = self.window.firstDate.date().toPyDate() # Generate start and end date based on dates if firstDate < secondDate: startDate = datetime.combine(firstDate, datetime.min.time()) endDate = datetime.combine(secondDate, datetime.max.time()) else: endDate = datetime.combine(firstDate, datetime.max.time()) startDate = datetime.combine(secondDate, datetime.min.time()) # Get rows between start and end date rows = self.DB.getDataBetween(startDate.timestamp(), endDate.timestamp()) # define QLineSeries instants temperatureSeries = QLineSeries() pressureSeries = QLineSeries() LightIntensitySeries = QLineSeries() humiditySeries = QLineSeries() windSpeedSeries = QLineSeries() # Fill series with db data for row in rows: temperatureSeries.append(int(row[6] * 1000), row[0]) pressureSeries.append(int(row[6] * 1000), row[1]) LightIntensitySeries.append(int(row[6] * 1000), row[2]) humiditySeries.append(int(row[6] * 1000), row[3]) windSpeedSeries.append(int(row[6] * 1000), row[4]) # Update series with new ones self.temperatureChart.setSeries(temperatureSeries) self.pressureChart.setSeries(pressureSeries) self.LightIntensityChart.setSeries(LightIntensitySeries) self.humidityChart.setSeries(humiditySeries) self.windSpeedChart.setSeries(windSpeedSeries)
class MainWindowController(object): def __init__(self): self.app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.MainWindow) self.pathQueue = [] self.__setup() self.init_frm() def __setup(self): self.ui.pbApply.clicked.connect(self.onClicked_Apply) self.ui.pbOpenSrcFolder.clicked.connect(self.onClicked_SrcPath) self.ui.pbOpenDestFolder.clicked.connect(self.onClicked_DestPath) def openFolder(self): dialog = QtWidgets.QFileDialog() dialog.setFileMode(QtWidgets.QFileDialog.FileMode()) dir = dialog.getExistingDirectory(None, 'Open a folder') return dir def init_frm(self): self.ui.pbApply.setEnabled(False) self.ui.pbStatus.setValue(100) def setEnableCtrs(self, enable): self.ui.pbApply.setEnabled(enable) self.ui.pbOpenSrcFolder.setEnabled(enable) self.ui.pbOpenDestFolder.setEnabled(enable) def enableBtnApply(self): srcPath = self.ui.leSrcPath.text() destPath = self.ui.leDestPath.text() if len(srcPath) > 0 and len(destPath) > 0: self.ui.pbApply.setEnabled(True) else: self.ui.pbApply.setEnabled(False) def onClicked_SrcPath(self): path = self.openFolder() self.ui.leSrcPath.setText(path) self.enableBtnApply() paths = "" for root, _, files in os.walk(path): for filename in files: x = os.path.join(root, filename) if os.path.isfile(x): isImg = imghdr.what(x) if isImg: paths += x + '\n' queue.heappush(self.pathQueue, x) else: print('Not an image') self.ui.plainTextEdit.setPlainText(paths) def onClicked_DestPath(self): self.ui.leDestPath.setText(self.openFolder()) self.enableBtnApply() def onClicked_Apply(self): self.ui.pbStatus.setMaximum(len(self.pathQueue)) qtd = 0 dest = self.ui.leDestPath.text().replace("\\", "/") while len(self.pathQueue) > 0: path = queue.heappop(self.pathQueue) path = path.replace("\\", "/") srcImg = cv2.imread(path) if (srcImg is None): print("Imagem nula:", path) else: aux_name = re.split('\/', path)[-1] name = '' for i in range(len(aux_name) - 4): name += aux_name[i] efx = Efx(srcImg, name) if self.ui.cbFlipH.isChecked(): efx.filpH(dest, name) if self.ui.cbFlipV.isChecked(): efx.filpV(dest, name) if self.ui.cbBlur.isChecked(): efx.blur(dest, name) if self.ui.cbGrayScale.isChecked(): efx.grayScale(dest, name) if self.ui.cbBrightness.isChecked(): efx.filter_brightnes_contrast(dest, name, 30, 1) #efx.filter_brightnes_contrast(dest,name,-30,1) #efx.filter_brightnes_contrast(dest,name,50,1) efx.filter_brightnes_contrast(dest, name, -50, 1) if self.ui.cbContrast.isChecked(): #efx.filter_brightnes_contrast(dest,name,0,0.6) #efx.filter_brightnes_contrast(dest,name,0,0.7) #efx.filter_brightnes_contrast(dest,name,0,0.8) efx.filter_brightnes_contrast(dest, name, 0, 1.2) pass if self.ui.cbRotationAnt.isChecked(): efx.rotate(dest, name, -2) efx.rotate(dest, name, -3) efx.rotate(dest, name, -5) efx.rotate(dest, name, -7) if self.ui.cbRotationAnt.isChecked(): efx.rotate(dest, name, 2) efx.rotate(dest, name, 3) efx.rotate(dest, name, 5) efx.rotate(dest, name, 7) qtd += 1 self.ui.pbStatus.setValue(qtd) self.ui.lbQtdImages.setText("{} Imagens".format(qtd)) self.ui.plainTextEdit.setPlainText("Finished")