def __create_signals(self): ''' Creates signals from the output file just created. :return: True if we created the signals. ''' loader = AutoWavLoader(self.__preferences) output_file = self.__executor.get_output_path() if os.path.exists(output_file): from app import wait_cursor with wait_cursor(f"Creating signals for {output_file}"): logger.info(f"Creating signals for {output_file}") name_provider = lambda channel, channel_count: get_channel_name( self.signalName.text(), channel, channel_count, channel_layout_name=self.__executor.channel_layout_name) loader.load(output_file) signal = loader.auto_load(name_provider, self.decimateAudio.isChecked()) self.__signal_model.add(signal) return True else: msg_box = QMessageBox() msg_box.setText( f"Extracted audio file does not exist at: \n\n {output_file}") msg_box.setIcon(QMessageBox.Critical) msg_box.setWindowTitle('Unexpected Error') msg_box.exec() return False
def _on_export_data(self): """ Handler function that is called when the Export Data button is pressed """ all_filters = ";;".join(['*.ecsv']) path, fmt = compat.getsavefilename(filters=all_filters) if path and fmt: try: plot_data_item = self.current_item self.export_data_item(plot_data_item, path, fmt) message_box = QMessageBox() message_box.setText("Data exported successfully.") message_box.setIcon(QMessageBox.Information) message_box.setInformativeText( "Data set '{}' has been exported to '{}'".format( plot_data_item.data_item.name, path)) message_box.exec() except Exception as e: logging.error(e) message_box = QMessageBox() message_box.setText("Error exporting data set.") message_box.setIcon(QMessageBox.Critical) message_box.setInformativeText("{}\n{}".format( sys.exc_info()[0], sys.exc_info()[1].__repr__()[:100])) message_box.exec()
def _select_spectra_to_load(self, specs_by_name): selection_dialog = SpectrumSelection(self) selection_dialog.populate(specs_by_name.keys()) selection_dialog.exec_() names_to_keep = selection_dialog.get_selected() if not names_to_keep: logging.warning('No spectra selected') message_box = QMessageBox() message_box.setText("No spectra were selected.") message_box.setIcon(QMessageBox.Warning) message_box.setInformativeText('No data has been loaded.') message_box.exec() return {} to_load = OrderedDict() for name, spectrum in specs_by_name.items(): if name in names_to_keep: to_load[name] = spectrum return to_load
def alert_on_change(self, title, text='Change will not take effect until the application is restarted', icon=QMessageBox.Warning): msg_box = QMessageBox() msg_box.setText(text) msg_box.setIcon(icon) msg_box.setWindowTitle(title) msg_box.exec()
def show_simple_dialog(message, title=""): msg_box = QMessageBox() msg_box.setIcon(QMessageBox.Information) msg_box.setText(message) msg_box.setWindowTitle(title) msg_box.setStandardButtons(QMessageBox.Ok) msg_box.exec()
def __save_report(self): ''' writes the figure to the specified format ''' formats = "Report Files (*.png *.jpg *.jpeg)" file_name = QFileDialog.getSaveFileName(parent=self, caption='Export Report', filter=formats) if file_name: output_file = str(file_name[0]).strip() if len(output_file) == 0: return else: format = os.path.splitext(output_file)[1][1:].strip() if format in VALID_IMG_FORMATS: scale_factor = self.widthPixels.value() / self.__x from app import wait_cursor with wait_cursor(): self.__status_bar.showMessage( f"Saving report to {output_file}", 5000) self.preview.canvas.figure.savefig(output_file, format=format, dpi=self.__dpi * scale_factor, pad_inches=0, bbox_inches='tight') self.__status_bar.showMessage( f"Saved report to {output_file}", 5000) else: msg_box = QMessageBox() msg_box.setText( f"Invalid output file format - {output_file} is not one of {VALID_IMG_FORMATS}" ) msg_box.setIcon(QMessageBox.Critical) msg_box.setWindowTitle('Unexpected Error') msg_box.exec()
def save_register_new_loader(self, filename): filename = "{}.py".format( filename) if not filename.endswith(".py") else filename string = self.as_new_loader() with open(filename, 'w') as f: f.write(string) # If a loader by this name exists, delete it if self.new_loader_dict['name'] in registry.get_formats()['Format']: registry.unregister_reader(self.new_loader_dict['name'], Spectrum1D) registry.unregister_identifier(self.new_loader_dict['name'], Spectrum1D) # Add new loader to registry spec = importlib.util.spec_from_file_location( os.path.basename(filename)[:-3], filename) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) message_box = QMessageBox() message_box.setText("Loader saved successful.") message_box.setIcon(QMessageBox.Information) message_box.setInformativeText("Custom loader was saved successfully.") message_box.exec()
def show_error(self): """This class create error dialog and show it""" if self.error is None: return from PartSeg.common_gui.error_report import ErrorDialog if isinstance(self.error, TiffFileException): mess = QMessageBox() mess.setIcon(QMessageBox.Critical) mess.setText("During read file there is an error: " + self.error.args[0]) mess.setWindowTitle("Tiff error") mess.exec() return if isinstance(self.error, SegmentationLimitException): mess = QMessageBox() mess.setIcon(QMessageBox.Critical) mess.setText( "During segmentation process algorithm meet limitations:\n" + "\n".join(self.error.args)) mess.setWindowTitle("Segmentation limitations") mess.exec() return dial = ErrorDialog(self.error, "Exception during program run") # TODO check # dial.moveToThread(QApplication.instance().thread()) dial.exec()
def _load_settings(self): ''' Since the settings file is modified by an external program, load_settings() must wait some delay to allow the file to be completely written. This function does the actually settings load. ''' # Make sure the settings exist. if not os.path.isfile(SETTINGS_PATH): shutil.copy(DEFAULT_SETTINGS_PATH, SETTINGS_PATH) # Make sure the settings are being watched. Note that this needs to be outside of the # existence check above, otherwise the settings won't be watched if they already exist. if len(self._settings_watcher.files()) == 0: self._settings_watcher.addPath(SETTINGS_PATH) try: self._settings = extended_json.load_file(SETTINGS_PATH) except extended_json.JSONSyntaxError as error: message_box = QMessageBox( QMessageBox.Critical, 'Error', f'{error.msg}\n{error.context()}' ) message_box.setFont(QFont('Consolas')) message_box.exec() if self._settings is None: sys.exit() self._apply_theme_settings() # Update the setting of all the open project widgets. projects = (self._tab_widget.widget(index) for index in range(self._tab_widget.count())) for project in projects: project.update_settings(self._settings)
def new_pydm_process(self, ui_file, macros=None, command_line_args=None): kwargs = copy.deepcopy( { "displayfile": ui_file, "macros": macros, "hide_nav_bar": self.hide_nav_bar, "hide_menu_bar": self.hide_menu_bar, "hide_status_bar": self.hide_status_bar, "read_only": pydm.data_plugins.is_read_only(), } ) kwargs_str = json.dumps(kwargs) python_exe = sys.executable if not self._generic_launcher_file_path: msg = f"Failed to launch pydm process, '{self._generic_launcher_file_name}' not found in path. Using python '{python_exe}'" logger.error(msg) box = QMessageBox(QMessageBox.Critical, "New PyDM Process Error", msg) box.exec() return logger.info(f"Init New PyDM Processs - {ui_file}") logger.info(f"Params: {kwargs_str}") subprocess.Popen( [self._generic_launcher_file_path, kwargs_str], shell=False, )
def __save_pixel_perfect(self): ''' saves an image based on passing the image through directly ''' if len(self.image.text()) > 0: file_name = QFileDialog.getSaveFileName(parent=self, caption='Export Report', filter='Report File (*.jpg *.png *.jpeg)') if file_name: output_file = str(file_name[0]).strip() if len(output_file) == 0: return else: format = os.path.splitext(output_file)[1][1:].strip() if format in VALID_IMG_FORMATS: from app import wait_cursor with wait_cursor(): self.__status_bar.showMessage(f"Saving report to {output_file}", 5000) self.preview.canvas.figure.savefig(output_file, format=format, dpi=self.__dpi) if self.__concat_images(format, output_file): self.__status_bar.showMessage(f"Saved report to {output_file}", 5000) else: msg_box = QMessageBox() msg_box.setText(f"Invalid output file format - {output_file} is not one of {VALID_IMG_FORMATS}") msg_box.setIcon(QMessageBox.Critical) msg_box.setWindowTitle('Unexpected Error') msg_box.exec() else: msg_box = QMessageBox() msg_box.setText('Unable to create report, no image selected') msg_box.setIcon(QMessageBox.Information) msg_box.setWindowTitle('No Image') msg_box.exec()
def load_data(self, file_path, file_loader, display=False): """ Load spectral data given file path and loader. Parameters ---------- file_path : str Path to location of the spectrum file. file_loader : str Format specified for the astropy io interface. display : bool Automatically add the loaded spectral data to the plot. Returns ------- : :class:`~specviz.core.items.DataItem` The `DataItem` instance that has been added to the internal model. """ try: spec = Spectrum1D.read(file_path, format=file_loader) name = file_path.split('/')[-1].split('.')[0] data_item = self.model.add_data(spec, name=name) return data_item except: message_box = QMessageBox() message_box.setText("Error loading data set.") message_box.setIcon(QMessageBox.Critical) message_box.setInformativeText("{}\n{}".format( sys.exc_info()[0], sys.exc_info()[1])) message_box.exec()
def _on_export_data(self): """ Handler function that is called when the Export Data button is pressed """ all_filters = ";;".join(['*.ecsv']) path, fmt = compat.getsavefilename(filters=all_filters) if path and fmt: try: plot_data_item = self.current_item self.export_data_item(plot_data_item, path, fmt) message_box = QMessageBox() message_box.setText("Data exported successfully.") message_box.setIcon(QMessageBox.Information) message_box.setInformativeText( "Data set '{}' has been exported to '{}'".format( plot_data_item.data_item.name, path)) message_box.exec() except Exception as e: logging.error(e) message_box = QMessageBox() message_box.setText("Error exporting data set.") message_box.setIcon(QMessageBox.Critical) message_box.setInformativeText( "{}\n{}".format( sys.exc_info()[0], sys.exc_info()[1].__repr__()[:100]) ) message_box.exec()
def slot_load_qstandard_clicked(self, result): self._recover_after_compute(self.slot_load_qstandard_clicked) if result["success"]: selected_standard = result["selected_standard"] msg = f"QS: '{selected_standard['name']}'" if self.gpc.is_quant_standard_custom(selected_standard): msg += " (user-defined)" self.le_param_fln.setText(msg) self.gpc.process_peaks_from_quantitative_sample_data() self._set_fit_status(False) self.gui_vars["gui_state"]["state_model_exists"] = True self.gui_vars["gui_state"]["state_model_fit_exists"] = False self.signal_model_loaded.emit(True) self.update_global_state.emit() else: msg = result["msg"] msgbox = QMessageBox(QMessageBox.Critical, "Failed to Load Quantitative Standard", msg, QMessageBox.Ok, parent=self) msgbox.exec()
def new_message_box(self, text, info=None, icon=QMessageBox.Warning): message_box = QMessageBox() message_box.setText(text) message_box.setIcon(icon) if info is not None: message_box.setInformativeText(info) message_box.exec() return
def show_failure_msg(self, msg, info, details): self.viz_tab.set_message(msg) msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setText(msg) msgBox.setInformativeText(info) msgBox.setDetailedText(details) msgBox.exec()
def show_warning(self): """show warning :py:class:`PyQt5.QtWidgets.QMessageBox`""" if not isinstance(self.warning, (list, tuple)) or self.warning[0] is None: return message = QMessageBox(QMessageBox.Warning, self.warning[0], self.warning[1], QMessageBox.Ok) message.exec()
def show_about(self): msg_box = QMessageBox() msg_box.setText( f"<a href='https://github.com/3ll3d00d/qvibe-analyser'>QVibe Analyser</a> v{self.__version} by 3ll3d00d" ) msg_box.setIcon(QMessageBox.Information) msg_box.setWindowTitle('About') msg_box.exec()
def showAbout(self): ''' Shows the about dialog ''' msg_box = QMessageBox() msg_box.setText( f"<a href='https://github.com/3ll3d00d/pypolarmap'>pypolarmap</a> v{self.__version} by 3ll3d00d" ) msg_box.setIcon(QMessageBox.Information) msg_box.setWindowTitle('About') msg_box.exec()
def __alert_on_version_check_fail(message): ''' Displays an alert if the version check fails. :param message: the message. ''' msg_box = QMessageBox() msg_box.setText(message) msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle('Unable to Complete Version Check') msg_box.exec()
def showMessage(title='', text='', icon=QMessageBox.NoIcon, windowIcon=QIcon(''), parent=None): """ Show a message box. """ message = QMessageBox(parent=parent) message.setWindowIcon(windowIcon) message.setIcon(icon) message.setWindowTitle(title) message.setText(text) message.setStandardButtons(QMessageBox.Ok) message.exec()
def show_warning_message(self, msg, problems): """Show warning message.""" text = msg + '\n\nVerify PVs:\n' for problem in problems: text += problem + '\n' mb = QMessageBox() mb.setMinimumSize(300, 150) mb.setWindowTitle('Message') mb.setIcon(QMessageBox.Warning) mb.setText(text) mb.exec()
def show_alert(title, message): ''' Shows an alert. :param title: the title :param message: the message. ''' msg_box = QMessageBox() msg_box.setText(message) msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle(title) msg_box.exec()
def action_online_docs_triggered(self): """ Display online documentation: open the URL in the default browser. """ doc_url = "http://nsls-ii.github.io/PyXRF/" try: webbrowser.open(doc_url, autoraise=True) except Exception as ex: logger.error(f"Error occurred while opening URL '{doc_url}' in the default browser") msg = f"Failed to Open Online Documentation. \n Exception: {str(ex)}" msgbox = QMessageBox(QMessageBox.Critical, "Error", msg, QMessageBox.Ok, parent=self) msgbox.exec()
def errorPopup(self, title, msg, details=None): """ Display an error popup to inform the user. Args: title (str): popup title msg (str): popup message details (str): facultative detailed text """ w = QMessageBox(QMessageBox.Critical, title, msg, QMessageBox.Ok, self) if details: w.setDetailedText(details) w.exec()
def __on_filter_save(self): ''' reacts to a filter being saved by redrawing the UI and syncing the filter to the HTP-1. ''' self.__magnitude_model.redraw() can_sync = len(self.__filters) == 16 self.applyFiltersButton.setEnabled(can_sync) if not can_sync: msg_box = QMessageBox() msg_box.setText(f"Too many filters loaded, remove {len(self.__filters) - 16} to be able to sync") msg_box.setIcon(QMessageBox.Warning) msg_box.setWindowTitle('Too Many Filters') msg_box.exec() if self.autoSyncButton.isChecked() and can_sync: self.send_filters_to_device()
def display_load_data_error(self, exp): """ Display error message box when attempting to load a data set. Parameters ---------- exp : str Error text. """ message_box = QMessageBox() message_box.setText("Error loading data set.") message_box.setIcon(QMessageBox.Critical) message_box.setInformativeText(str(exp)) message_box.exec()
def show_remux_cmd(self): ''' Pops the ffmpeg command into a message box ''' if self.__executor is not None and self.__executor.filter_complex_script_content is not None: msg_box = QMessageBox() font = QFont() font.setFamily("Consolas") font.setPointSize(8) msg_box.setFont(font) msg_box.setText( self.__executor.filter_complex_script_content.replace( ';', ';\n')) msg_box.setIcon(QMessageBox.Information) msg_box.setWindowTitle('Remux Script') msg_box.exec()
def slot_preview_items_changed(self, result): if not result["success"]: # The error shouldn't actually happen here. This is to prevent potential crashes. msg = f"Error occurred: {result['msg']}.\nData may need to be reloaded to continue processing." msgbox = QMessageBox(QMessageBox.Critical, "Error", msg, QMessageBox.Ok, parent=self) msgbox.exec() # Here we want to expand the range in the Total Count Map preview if needed self.update_preview_map_range.emit("expand") self._recover_after_compute(self.slot_preview_items_changed)
def slot_channel_index_changed(self, result): self._recover_after_compute(self.slot_channel_index_changed) if result["success"]: self.signal_data_channel_changed.emit(True) else: self.signal_data_channel_changed.emit(False) msg = result["msg"] msgbox = QMessageBox(QMessageBox.Critical, "Error", msg, QMessageBox.Ok, parent=self) msgbox.exec()
def slot_apply_mask_clicked(self, result): if not result["success"]: msg = f"Error occurred while applying the ROI selection:\nException: {result['msg']}" logger.error(f"{msg}") mb_error = QMessageBox(QMessageBox.Critical, "Error", f"{msg}", QMessageBox.Ok, parent=self) mb_error.exec() # Here we want to expand the range in the Total Count Map preview if needed self.update_preview_map_range.emit("update") self._recover_after_compute(self.slot_apply_mask_clicked)
def _on_change_color(self): """ Listens for color changed events in plot windows, gets the currently selected item in the data list view, and changes the stored color value. """ # If there is no currently selected rows, raise an error if self.current_item is None: message_box = QMessageBox() message_box.setText("No item selected, cannot change color.") message_box.setIcon(QMessageBox.Warning) message_box.setInformativeText( "There is currently no item selected. Please select an item " "before changing its plot color.") message_box.exec() return color = QColorDialog.getColor(options=QColorDialog.ShowAlphaChannel) if color.isValid(): self.current_item.color = color.toRgb() self.color_changed.emit(self.current_item, self.current_item.color)