def add_hex_editor_dock(self, rom_variant: RomVariant, object_name: str) -> HexViewerController: ''' Internally used to add a new or existing hex editor ''' rom = get_rom(rom_variant) if rom is None: QMessageBox.critical(self.parent, 'Load ROM', f'Unable to load rom {rom_variant}') return None dockWidget = HexViewerDock(self.parent, 'Hex Viewer ' + rom_variant) # Not only hide docks on close TODO still remove them here dockWidget.setAttribute(Qt.WA_DeleteOnClose) dockWidget.setObjectName(object_name) self.parent.addDockWidget(Qt.DockWidgetArea.TopDockWidgetArea, dockWidget) controller = HexViewerController(dockWidget, rom_variant, rom) self.hex_viewer_manager.register_controller(controller) dock = Dock(object_name, dockWidget, rom_variant, controller) self.docks[object_name] = dock dockWidget.destroyed.connect(lambda: self.remove_dock(object_name)) return controller
def showDialog(self, text: str, title: str, buttons, callback): dialog = QMessageBox(self.window) dialog.setWindowTitle(title) dialog.setText(text) dialog.setStandardButtons(buttons) dialog.buttonClicked.connect(callback) dialog.exec_()
def load(self): axSelect = QAxSelect(self) if axSelect.exec_() == QDialog.Accepted: clsid = axSelect.clsid() if not self.axWidget.setControl(clsid): QMessageBox.warning(self, "AxViewer", "Unable to load " + clsid + ".")
def _training_complete_event(self, return_value: float) -> None: """Display information about completed model training.""" QMessageBox.information( self, self.tr("Information"), f'Model created and saved with final R-Squared of: {return_value}', QtWidgets.QMessageBox.Ok) self.setEnabled(True)
def on_search_complete(self, dicom_structure): """ Executes once the directory search is complete. :param dicom_structure: DICOMStructure object constructed by the directory search. """ self.open_patient_directory_choose_button.setEnabled(True) self.open_patient_window_stop_button.setVisible(False) self.open_patient_window_patients_tree.clear() # dicom_structure will be None if function was interrupted. if dicom_structure is None: return for patient_item in dicom_structure.get_tree_items_list(): self.open_patient_window_patients_tree.addTopLevelItem( patient_item) patient_item.setExpanded(True) # Display all studies # Display all image sets for i in range(patient_item.childCount()): study = patient_item.child(i) study.setExpanded(True) if len(dicom_structure.patients) == 0: QMessageBox.about(self, "No files found", "Selected directory contains no DICOM files.")
def check_input(self): name = self.txtName.text() path = self.txtPath.text() password1 = self.txtPassword1.text() password2 = self.txtPassword2.text() illegal, msg = Key.is_password_illegal(password1) if illegal: QMessageBox.critical(self, "错误", msg) return False if password1 != password2: QMessageBox.critical(self, "错误", "两次输入的密码不一致") return False if len(name.strip()) == 0: QMessageBox.critical(self, "错误", "名称不能为空") return False if len(path.strip()) == 0: QMessageBox.critical(self, "错误", "路径不能为空") return False if os.path.exists(path): QMessageBox.critical(self, "错误", "目标文件已经存在") return False return True
def open_news(self): if not os.path.isfile("NEWS.txt"): QMessageBox.question(self, "Внимание!", "Файл \"NEWS.txt\" не был обнаружен в директории с исполняемым \ файлом. Для ознакомления со списком изменений вы можете обратиться к репозиторию на GitHub по ссылке выше.", QMessageBox.Ok) else: os.startfile("NEWS.txt")
def roi_saved(self, new_rtss): """ Create a new ROI in Structure Tab and notify user """ new_roi_name = self.new_roi_name_line_edit.text() self.signal_roi_manipulated.emit((new_rtss, {"draw": new_roi_name})) QMessageBox.about(self.manipulate_roi_window_instance, "Saved", "New contour successfully created!") self.close()
def callBack(self, keys): # do nothing if keys is empty if not (keys): return # check that if shortcut used before. if keys in self.shortcuts_list: self.msgBox = QMessageBox() self.msgBox.setText( QCoreApplication.translate( "setting_src_ui_tr", "<b><center>This shortcut has been used before!\ Use another one!</center></b>")) self.msgBox.setIcon(QMessageBox.Warning) reply = self.msgBox.exec_() # set new shortcut else: selected_row = self.shortcut_table.selectionModel().selectedRows( )[0].row() item = QTableWidgetItem(keys) # align center item.setTextAlignment(0x0004 | 0x0080) # insert item in shortcut_table self.shortcut_table.setItem(selected_row, 1, item) # set keys in shortcuts_list self.shortcuts_list[selected_row] = keys
def searchPlayer(self, text, combobox): # It even searches the player for you. What more could you want? search_index = combobox.findText(text, QtCore.Qt.MatchContains) if search_index == -1: QMessageBox.warning(self, "Error", "No player found") else: combobox.setCurrentIndex(search_index)
def ExportTeams(self): export_dir = self.config["save_route"] if self.config["save_route"] \ is not None else THISDIR exported_file = QFileDialog.getSaveFileName(self, "Save File", export_dir, "Save files (*.zip)") if exported_file[0] != "": export_filename = exported_file[0] if export_filename.endswith(".zip") is False: export_filename += ".zip" files_to_export = [] files_to_export.append("config\\teams.json") for root, directories, files in os.walk(THISDIR+"\\images\\logos"): for filename in files: filepath = os.path.join(root, filename) files_to_export.append(filepath) with ZipFile(export_filename, "w") as export_zip: for exp_file in files_to_export: export_name = exp_file if exp_file.endswith(".json"): split_name = exp_file.split("\\") export_name = split_name[-1] if exp_file.endswith(".png"): split_name = exp_file.split("\\") export_name = "\\logos\\" + split_name[-1] export_zip.write(exp_file, arcname=export_name) export_zip.close() if os.path.exists(export_filename): QMessageBox.information(self, "Export", "The export was successful")
def taskStart(self): ''' Inicia a execucao do programa, se houver algum erro durante o processo notifica o usuario e deixa a funcao imediatamente''' if self.folder.isModified() and self.path.isModified(): # o usuario entrou com os enderecos? start = time.time() # Conhece do que se trata cada coluna na tabela e armazena essa informacao. header = {} for col in range(15): header[self.Tabela.cellWidget(0, col).currentText()] = col boolean = 0 if self.ignore.isChecked() else None # Le o arquivo e retorna um dataframe de strings df_master = utils.read_file(self, header = boolean) df_master = dt.data_filter(self, df_master, header) df_master = dt.convert_dtype(self, df_master) # Computa os acumulados para cada intervalo de tempo (key). for key in self.selected: array = dt.compute(df_master.index.to_numpy(), df_master['Observado'].to_numpy(), key) df_master[self.linktimedelta[key]] = pd.Series(array, df_master.index) # salva o arquivo final. utils.save_file(self, df_master) # Fim do processo end = time.time() # Notifica o usuario QMessageBox.information(self, "Notificação", "Tarefa realizada com sucesso!\nTempo de execução: {} s.".format(round(end-start, 2))) # Reseta a tabela e os endereço do arquivo aberto e onde salvar, na janela principal. self.resetProgram() else: QMessageBox.warning(self, "Notificação", "Houve um erro no arquivo ou diretório especificado.\nPor favor, selecione um caminho válido.")
def CheckForKill(self): if AppGlobals.ProgramRunner().GetTickDelta() > 2: self.updateWorker.terminate() self.updateWorker.wait() AppGlobals.ProgramRunner().StopAll() self.updateWorker.start() QMessageBox.critical(self, "Timeout", "Program timed out.")
def CloseChip(self) -> bool: if AppGlobals.ProgramRunner().runningPrograms: status = QMessageBox.question( self, "Confirm", "There is a program running. Are you sure you want to stop?") if status is not QMessageBox.Yes: return False AppGlobals.ProgramRunner().StopAll() if self._editorWindow.isVisible(): if not self._editorWindow.RequestCloseAll(): return False if AppGlobals.Chip().modified: ret = QMessageBox.warning( self, "Confirm", "The current chip project has been modified.\nDo you want to save changes?", QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel, QMessageBox.Save) if ret is QMessageBox.Save: if not self.SaveChip(): return False elif ret is QMessageBox.Cancel: return False return True
def remove_key_action(self): selected = self.keyListView.selectedIndexes() if not selected: return index = selected[0] self._remove_key(index.row()) QMessageBox.information(self, '信息', '密钥已经移除')
def accepting(self): # Check that no mandatory input is empty if self.name.text( ) != '' and self.scan_text.text() != '' and self.upper_level_text.text( ) != '' and self.lower_level_text.text() != '': # Check validation if re.match(r'^([\s\d]+)$', self.upper_level_text.text()) and re.match( r'^([\s\d]+)$', self.lower_level_text.text()): self.accept() # The level fields do not contain just numbers else: button_reply = QMessageBox.warning( self, "Error Message", "The level fields need to be numbers!", QMessageBox.Ok) if button_reply == QMessageBox.Ok: pass # Atleast one input field was left empty else: button_reply = QMessageBox.warning( self, "Error Message", "None of the fields should be empty!", QMessageBox.Ok) if button_reply == QMessageBox.Ok: pass
def reload_key_action(self): item = self.get_selected_item() key: Key = item.data() password = None if Key.need_password(key.path): ok_pressed = True while ok_pressed: password, ok_pressed = QInputDialog.getText( self, "需要密码", "输入密码:", QLineEdit.Password, "") if ok_pressed: illegal, msg = Key.is_password_illegal(password) if illegal: QMessageBox.information(self, '错误', msg) continue break else: return try: key.load(key.path, password) except Exception as e: QMessageBox.critical(self, '错误', '不是有效的密钥文件<br/>' + str(e)) return self.update_key_icon(item)
def load_symbols(self, rom_variant: RomVariant, silent: bool) -> None: maps = { RomVariant.CUSTOM: 'tmc.map', RomVariant.CUSTOM_EU: 'tmc_eu.map', RomVariant.CUSTOM_JP: 'tmc_jp.map', RomVariant.CUSTOM_DEMO_USA: 'tmc_demo_usa.map', RomVariant.CUSTOM_DEMO_JP: 'tmc_demo_jp.map', } map_file = path.join(settings.get_repo_location(), maps[rom_variant]) if not path.isfile(map_file): if silent: print(f'Could not find tmc.map file at {map_file}.') else: QMessageBox.critical( self, 'Load symbols from .map file', f'Could not find tmc.map file at {map_file}.') return get_symbol_database().load_symbols_from_map(rom_variant, map_file) if not silent: QMessageBox.information( self, 'Load symbols', f'Successfully loaded symbols for {rom_variant} rom from tmc.map file.' )
def about(self): QMessageBox.about( self, "About Dock Widgets", "The <b>Dock Widgets</b> example demonstrates how to use " "Qt's dock widgets. You can enter your own text, click a " "customer to add a customer name and address, and click " "standard paragraphs to add them.")
def _handle_file_open(self): if self.config_has_changes: msg = QMessageBox( QMessageBox.Warning, "Are you sure?", ("You have unsaved changes to your current config. " "If you continue all unsaved changes will be lost."), buttons=QMessageBox.Open | QMessageBox.Cancel, ) if msg.exec_() == QMessageBox.Cancel: return file_path = QFileDialog.getOpenFileName( self, caption="Open a new config...", dir=os.getcwd(), filter="Config Files (*.yml *.yaml)", )[0] if file_path: self.reset_changes(file_path) # update the new log location self.update_log_paths(file_path) # setup the config tabs self.initialise_config_tabs(self.config)
def submitAll(self): result = super().submitAll() if result: self._deleted_rows = [] else: error_code = self.lastError().nativeErrorCode() if error_code == '1299': prefix = "NOT NULL constraint failed: " + self.tableName( ) + "." if self.lastError().databaseText().startswith(prefix): field_name = self.lastError().databaseText()[len(prefix):] header_title = self.tableName() + ":" + self.headerData( self.fieldIndex(field_name)) QMessageBox().warning( self._view, self.tr("Data are incomplete"), self.tr("Column has no valid value: " + header_title), QMessageBox.Ok) else: logging.fatal( self.tr("Submit failed: ") + decodeError(self.lastError().text())) elif error_code == '1811': # Foreign key constraint failed QMessageBox().warning( self._view, self.tr("Data are in use"), self. tr("Data are referenced in another place and can't be modified" ), QMessageBox.Ok) else: logging.fatal( self.tr("Submit failed: ") + decodeError(self.lastError().text())) return result
def pyradiomics_handler(self, path, filepaths, hashed_path): """ Sends signal to initiate pyradiomics analysis """ if which('plastimatch') is not None: if hashed_path == '': confirm_pyradi = QMessageBox.information( self, "Confirmation", "Are you sure you want to perform pyradiomics? Once " "started the process cannot be terminated until it " "finishes.", QMessageBox.Yes, QMessageBox.No) if confirm_pyradi == QMessageBox.Yes: self.run_pyradiomics.emit(path, filepaths, hashed_path) if confirm_pyradi == QMessageBox.No: pass else: self.run_pyradiomics.emit(path, filepaths, hashed_path) else: exe_not_found = QMessageBox.information( self, "Error", "Plastimatch not installed. Please install Plastimatch " "(https://sourceforge.net/projects/plastimatch/) to carry out " "pyradiomics analysis. If using Windows, please ensure that " "your system's PATH variable inlcudes the directory where " "Plastimatch's executable is installed.")
def info(self): self.popup = QMessageBox(QMessageBox.Information, "Sobre", "Informações") self.popup.setInformativeText("""Clientes \nVersão 0.5 \nFeito com S2 por Zero \nMIT License""") self.popup.addButton(QMessageBox.Ok) self.popup.exec()
def slot_show_goto_dialog(self): (input_str, res) = QInputDialog.getText( self.dock, 'Goto', 'Enter local address to jump to') if res: # Parse as hex (TODO maybe as decimal, if no 0x and no ABCDEF) # TODO handle errors try: local_address = int(input_str, 16) except ValueError: # maybe it is a symbol? if self.symbols is not None: symbol = self.symbols.find_symbol_by_name(input_str) if symbol is not None: local_address = symbol.address else: QMessageBox.critical(self.parent(), 'Goto', f'{input_str} is not an address or symbol.') return else: QMessageBox.critical(self.parent(), 'Goto', f'{input_str} is not an address and symbols are not loaded for {self.rom_variant}.') return if local_address > ROM_OFFSET: local_address -= ROM_OFFSET # TODO error for everything that is not in [0x00000000, 0x00FFFFFF] or [0x08000000, 0x08FFFFFF] self.update_cursor(self.address_resolver.to_virtual(local_address))
def openSelectedFiles(self): failedToOpen = [] files = set() for index in self.tree.selectionModel().selectedIndexes(): if self.model.fileInfo(index).isFile(): files.add(self.model.fileInfo(index).absoluteFilePath()) for filename in files: QSettings().setValue("triage/recentFile", filename) f = FileContext.openFilename(filename) if not f: failedToOpen.append(filename) continue for data in f.getAllDataViews(): Settings().set_string("analysis.mode", Settings().get_string("triage.analysisMode"), data) Settings().set_bool("triage.preferSummaryView", True, data) if data.view_type != "Raw": linearSweepMode = Settings().get_string("triage.linearSweep") if linearSweepMode == "none": Settings().set_bool("analysis.linearSweep.autorun", False, data) elif linearSweepMode == "partial": Settings().set_bool("analysis.linearSweep.autorun", True, data) Settings().set_bool("analysis.linearSweep.controlFlowGraph", False, data) elif linearSweepMode == "full": Settings().set_bool("analysis.linearSweep.autorun", True, data) Settings().set_bool("analysis.linearSweep.controlFlowGraph", True, data) self.context.openFileContext(f) if len(failedToOpen) > 0: QMessageBox.critical(self, "Error", "Unable to open:\n" + "\n".join(failedToOpen))
def _prediction_historical_error(self, prediction: list) -> None: """Displays a message for when historical target is unavalable such that a graph can't be made.""" QMessageBox.information( self, self.tr("Information"), f'Prediction was: {prediction}. \n ' 'Unable to display graph due to missing historical data.', QtWidgets.QMessageBox.Ok)
def slot_remove_redundant(self) -> None: ''' Disables all constraints that only contain redundant information and don't create more relations ''' progress_dialog = self.api.get_progress_dialog( 'Constraint Cleaner', 'Removing redundant constraints...', False) progress_dialog.show() self.thread = QThread() self.worker = RemoveRedundantWorker() self.worker.moveToThread(self.thread) self.worker.signal_progress.connect( lambda progress: progress_dialog.set_progress(progress)) self.worker.signal_done.connect( lambda: ( # https://stackoverflow.com/a/13672943 self.thread.quit(), progress_dialog.close(), QMessageBox.information( self.api.main_window, 'Constraint Cleaner', 'All redundant constraints are removed.'))) self.worker.signal_fail.connect(lambda: ( self.thread.quit(), progress_dialog.close(), QMessageBox.critical( self.api.main_window, 'Constraint Cleaner', 'Failed to add a constraint.\nSee console for more information.' ))) self.thread.started.connect(self.worker.process) self.thread.start()
def add_new_user(self): if self.login_thread is None: self.ui.setEnabled(False) self.login_thread = LoginThread(self.on_login) self.login_thread.start() QMessageBox.information( self, "Add new user", "Please log in to your YouTube account. " "The window will close automatically when you log in.")
def Sl_view_profile_logout(self): msg = QMessageBox(QMessageBox.Question, "Logout", "Siete sicuri di voler effettuare il logout?", QMessageBox.Yes | QMessageBox.No) msg.setButtonText(QMessageBox.Yes, "Sì") if msg.exec() == QMessageBox.Yes: self._net_model.logout() sys.exit()
def _setup_invalid_gui(self): not_available = QLabel('Data access unavailable') not_available.alignment = Qt.AlignCenter not_available.enabled = False layout = QGridLayout(self) layout.add_widget(not_available) QMessageBox.warning(self, 'Data access unavailable', 'Data access unavailable.')