def __read_slvs(self, file_name: str) -> None: """Read slvs format. + Choose a group. + Read the entities of the group. """ parser = SlvsParser(file_name) if not parser.is_valid(): QMessageBox.warning(self, "Format error", "The format is not support.") return groups = parser.get_groups() if not groups: QMessageBox.warning(self, "Format error", "The model file is empty.") return group, ok = QInputDialog.getItem( self, "Solvespace groups", "Choose a group:\n" "(Please know that the group must contain a sketch only.)", ["@".join(g) for g in groups], 0, False) if not ok: return self.clear() logger.debug(f"Read from group: {group}") self.parse_expression(parser.parse(group.split('@')[0]))
def _open_dialog(self, name, widget): if name == 'Collapse Cube': ex = collapse_cube.CollapseCube(self._data, parent=self, allow_preview=True) if name == 'Spatial Smoothing': ex = smoothing.SelectSmoothing(self._data, parent=self, allow_preview=True) if name == 'Arithmetic Operations': ex = arithmetic_gui.SelectArithmetic(self._data, self.session.data_collection, parent=self) if name == "Moment Maps": moment_maps.MomentMapsGUI(self._data, self.session.data_collection, parent=self) if name == 'Wavelength Units': current_unit = self._units_controller.units_titles.index( self._units_controller._new_units.long_names[0].title()) wavelength, ok_pressed = QInputDialog.getItem( self, "Pick a wavelength", "Wavelengths:", self._units_controller.units_titles, current_unit, False) if ok_pressed: self._units_controller.on_combobox_change(wavelength)
def add_selected_to_group(self, *args, **kwargs): # selected = self.ui.treeWidget_stations.selectedItems() # if selected: if self.selected_stations: groups = self.file_handler.get_groups() group_id, ok = QInputDialog.getItem(self, "Add Selected Items to Group", "Please select one group:", groups, 0, False) if ok and group_id: group_id = str(group_id) # for item in selected: for station in self.selected_stations: # if not item.parent(): # selected a group # selected_group_id = str(item.text(0)) # members = self.file_handler.get_group_members(selected_group_id) # if members: # for member in members: # self.file_handler.add_to_group(group_id, member) # else: # selected an item # ref = str(item.text(1)) # self.file_handler.add_to_group(group_id, ref) self.file_handler.add_to_group( group_id, self.file_handler.station2ref(station)) self.update_view()
def addChoice(self): if len(self._possible_items) == 0: QMessageBox.information( self, "No items", "No items available for selection!" ) else: item, ok = QInputDialog.getItem( self, "Select a case", "Select a case to add to the case list:", self._possible_items, ) if ok: item = str(item).strip() text = str(self._list_edit_line.text()).rstrip() if len(text) == 0: text = item + ", " elif text.endswith(","): text += " " + item else: text += ", " + item self._list_edit_line.setText(text)
def startTemplate(self, simulation=True): if not self._gui_node: logger.warning('Cannot start template without guiNode') return # Get list of templates files = dir(tGUIs) GUIlist = [] for name in files: if '__' not in name: GUIlist.append(name) # Ask user to select template message = 'Name of the Template to be used.' d = 0 options = GUIlist tName, ok = QInputDialog.getItem(None, 'Input', message, options, d, False) if not ok: return try: tGUI = getattr(tGUIs, tName) args, kwargs = tGUI() except AttributeError: message = 'That template was not found.' tName, ok = QInputDialog.getText(None, 'Input', message, QLineEdit.Normal) args = () kwargs = dict() self._gui_node.apparatus.applyTemplate(tName, args=args, kwargs=kwargs)
def _set_check_opmode(self): self.ok_ps.clear() self.nok_ps.clear() devices = self._get_selected_ps() devices = [ dev for dev in devices if dev.sec != 'LI' and dev.dev not in ('FCH', 'FCV') ] if not devices: return state, ok = QInputDialog.getItem(self, "OpMode Input", "Select OpMode: ", _PSE.OPMODES, editable=False) if not ok: return state2set = getattr(_PSC.OpMode, state) state2check = getattr(_PSC.States, state) task0 = CreateTesters(devices, parent=self) task1 = SetOpMode(devices, state=state2set, parent=self) task2 = CheckOpMode(devices, state=state2check, parent=self) task2.itemDone.connect(self._log) labels = [ 'Connecting to devices...', 'Setting PS OpMode to ' + state + '...', 'Checking PS OpMode in ' + state + '...' ] tasks = [task0, task1, task2] dlg = ProgressDialog(labels, tasks, self) dlg.exec_()
def __import_xlsx(self) -> None: """Paste path data from a Excel file.""" file_name = self.input_from( "Excel project", ["Microsoft Office Excel (*.xlsx *.xlsm *.xltx *.xltm)"] ) if not file_name: return wb = load_workbook(file_name) sheets = wb.get_sheet_names() name, ok = QInputDialog.getItem(self, "Sheets", "Select a sheet:", sheets, 0) if not ok: return def get_path(sheet: str) -> Iterator[_Coord]: """Keep finding until there is no value""" ws = wb.get_sheet_by_name(sheets.index(sheet)) i = 1 while True: sx = ws.cell(i, 1).value sy = ws.cell(i, 2).value if None in {sx, sy}: break try: yield float(sx), float(sy) except Exception as e: QMessageBox.warning(self, "File error", f"{e}") return i += 1 self.set_path(get_path(name))
def _addConfiguration(self): try: configs = self._model.getConfigurations() except Exception as e: self._showWarningBox(e, "Failed to retrieve configurations") else: if configs: options = [item["name"] for item in configs] config_name, ok = QInputDialog.getItem( self, "Available Configurations", "Select a configuration:", options, 0, False) if ok and config_name: if not self._isConfigurationLoaded(config_name): self._model.loadConfiguration(name=config_name) else: QMessageBox( QMessageBox.Information, "Configuration already loaded", "Configuration is already loaded.").exec_() # Highlight new column; or the one that is already loaded col = self._model.getConfigurationColumn(config_name) self.table.selectColumn(col) else: self._showMessageBox("No configuration found") return
def load_example(self, is_import: bool = False) -> bool: """Load example to new project.""" # load example by expression example_name, ok = QInputDialog.getItem(self, "Examples", "Select an example to load:", all_examples(), 0, False) if not ok: return False if not is_import: self.reset() self.main_clear() if self.prefer.open_project_actions_option == 1: self.command_stack.beginMacro("Add mechanism") expr, inputs = example_list(example_name) self.parse_expression(expr) if not is_import: if self.prefer.open_project_actions_option == 1: self.command_stack.endMacro() self.command_stack.beginMacro("Add inputs data") # Import without inputs data self.load_inputs(inputs) if self.prefer.open_project_actions_option == 0: self.command_stack.clear() self.command_stack.setUndoLimit(self.prefer.undo_limit_option) elif self.prefer.open_project_actions_option == 1: self.command_stack.endMacro() self.set_file_name(example_name, is_example=True) self.project_saved() logger.info(f"Example \"{example_name}\" has been loaded.") return True
def add_other_dialog(self): """ A QAction callback. Start a dialog to choose a name of a function except a peak or a background. The new function is added to the browser. """ selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select function', self.other_names, 0, False) if selected_name[1]: self.add_other_requested.emit(selected_name[0])
def add_peak_dialog(self): """ A QAction callback. Start a dialog to choose a peak function name. After that the tool will expect the user to click on the canvas to where the peak should be placed. """ selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select peak function', self.peak_names, self.peak_names.index(self.current_peak_type), False) if selected_name[1]: self.peak_type_changed.emit(selected_name[0]) self.mouse_state.transition_to('add_peak')
def getPreProcessingChoice(self, filename, filestructure): items = ("Choose the longest", "Merge all") item, okPressed = QInputDialog.getItem( self, "Multiple tracks/segments", "File '" + filename + "' contains more than one track/segment\n\n" + infos + "\nWhat to do?", items, 0, False) if okPressed and item: return items.index(item) else: return 0
def set_overplot_target(): item, ok = QInputDialog.getItem( self, "Select Tab", "Tab", tuple(self._title_to_tab), 0, False) if not ok: # Abort and fallback to Off. Would be better to fall back to # previous state (which could be latest_live) but it's not # clear how to know what that state was. self.off.setChecked(True) return self.set_overplot_state(OverPlotState.fixed) self._overplot_target = item
def add_peak_dialog(self): """ A QAction callback. Start a dialog to choose a peak function name. After that the tool will expect the user to click on the canvas to where the peak should be placed. """ selected_name = QInputDialog.getItem( self.canvas, 'Fit', 'Select peak function', self.peak_names, self.peak_names.index(self.current_peak_type), False) if selected_name[1]: self.peak_type_changed.emit(selected_name[0]) self.mouse_state.transition_to('add_peak')
def add_background_dialog(self): """ A QAction callback. Start a dialog to choose a background function name. The new function is added to the browser. """ current_index = self.background_names.index(self.default_background) if current_index < 0: current_index = 0 selected_name = QInputDialog.getItem(self.canvas, 'Fit', 'Select background function', self.background_names, current_index, False) if selected_name[1]: self.add_background_requested.emit(selected_name[0])
def prompt_hostname_gui(): """Ask user for a hostname, offer recently used values""" from qtpy.QtWidgets import QInputDialog from qtpy.QtCore import QSettings settings = QSettings('allegro', 'allegro_vnc') recent = settings.value('recent_hostnames', []) hostname, accepted = QInputDialog.getItem(None, 'Enter hostname', 'Hostname:', recent) if not accepted: return recent.insert(0, hostname) # Remove duplicates without changing order recent = sorted(set(recent), key=recent.index)[:10] settings.setValue('recent_hostnames', recent) return hostname
def edit_parameters(self): allaxes = self.canvas.figure.get_axes() if not allaxes: QMessageBox.warning(self.parent, "Error", "There are no axes to edit.") return if len(allaxes) == 1: axes = allaxes[0] else: titles = [] for axes in allaxes: title = axes.get_title() ylabel = axes.get_ylabel() label = axes.get_label() if title: fmt = "%(title)s" if ylabel: fmt += ": %(ylabel)s" fmt += " (%(axes_repr)s)" elif ylabel: fmt = "%(axes_repr)s (%(ylabel)s)" elif label: fmt = "%(axes_repr)s (%(label)s)" else: fmt = "%(axes_repr)s" titles.append(fmt % dict(title=title, ylabel=ylabel, label=label, axes_repr=repr(axes))) item, ok = QInputDialog.getItem(self.parent, 'Customize', 'Select axes:', titles, 0, False) if ok: axes = allaxes[titles.index(six.text_type(item))] else: return figureoptions.figure_edit(axes, self)
def _removeConfiguration(self): try: configs = self._model.getConfigurations() except Exception as e: self._showWarningBox(e, "Failed to retrieve configurations") else: if configs: # Show configs available options = [item["name"] for item in configs] config, ok = QInputDialog.getItem(self, "Available Configurations", "Select a configuration:", options, 0, False) if ok and config: # Ask for confirmation if self._isConfigurationLoaded(config): msg = ("Configuration is currenty loaded." "Delete it anyway?") else: msg = ("This will permanently delete configuration {}." "Proceed?").format(config) if self._showDialogBox(msg) == QMessageBox.Cancel: return # Delete configuration config = configs[options.index(config)] try: self._model.deleteConfiguration(config) except Exception as e: self._showWarningBox(e) else: self._showMessageBox( "Configuration {} was deleted.".format( config['name'])) else: self._showMessageBox("No configuration found") return
def main_gui(): from qtpy.QtWidgets import QInputDialog, QApplication, QMessageBox import sys _app = QApplication(sys.argv) hostname = prompt_hostname_gui() if not hostname: return try: displays = list_displays(hostname) except subprocess.CalledProcessError as e: QMessageBox.critical(None, 'Error listing displays', e.output) exit(-1) if not displays: try: display = create_display(hostname) except subprocess.CalledProcessError as e: QMessageBox.critical(None, 'Error creating display', e.output) exit(-1) elif len(displays) == 1: display = displays[0] else: display, accepted = QInputDialog.getItem(None, 'Select display', 'Display:', map(str, displays), editable=False) if not accepted: return display = int(display) try: print('Connecting to {}:{}'.format(hostname, display)) connect_viewer(hostname, display) except subprocess.CalledProcessError as e: QMessageBox.critical(None, 'Error connecting to display', e.output) exit(-1)
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name( key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals( self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s") % (self.filename, error_message)) self.refresh_table()
def _open_overplotted_on(self): item, ok = QInputDialog.getItem( self, "Select Tab", "Tab", self._tab_titles, 0, False) if not ok: return self.open.emit(item, self.entries)
def import_data(self, filenames=None): """Import data from text file""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question(self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?" ) % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) if self.is_internal_shell: self.editor.import_from_string(text) else: base_name = osp.basename(self.filename) editor = ImportWizard(self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() monitor_set_global(self._get_sock(), var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() if self.is_internal_shell: namespace, error_message = load_func(self.filename) interpreter = self.shellwidget.interpreter for key in list(namespace.keys()): new_key = fix_reference_name(key, blacklist=list(interpreter.namespace.keys())) if new_key != key: namespace[new_key] = namespace.pop(key) if error_message is None: interpreter.namespace.update(namespace) else: error_message = monitor_load_globals(self._get_sock(), self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical(self, title, _("<b>Unable to load '%s'</b>" "<br><br>Error message:<br>%s" ) % (self.filename, error_message)) self.refresh_table()
def import_data(self, filenames=None): """Import data from text file.""" title = _("Import data") if filenames is None: if self.filename is None: basedir = getcwd_or_home() else: basedir = osp.dirname(self.filename) filenames, _selfilter = getopenfilenames(self, title, basedir, iofunctions.load_filters) if not filenames: return elif is_text_string(filenames): filenames = [filenames] for filename in filenames: self.filename = to_text_string(filename) if os.name == "nt": self.filename = remove_backslashes(self.filename) ext = osp.splitext(self.filename)[1].lower() if ext not in iofunctions.load_funcs: buttons = QMessageBox.Yes | QMessageBox.Cancel answer = QMessageBox.question( self, title, _("<b>Unsupported file extension '%s'</b><br><br>" "Would you like to import it anyway " "(by selecting a known file format)?") % ext, buttons) if answer == QMessageBox.Cancel: return formats = list(iofunctions.load_extensions.keys()) item, ok = QInputDialog.getItem(self, title, _('Open file as:'), formats, 0, False) if ok: ext = iofunctions.load_extensions[to_text_string(item)] else: return load_func = iofunctions.load_funcs[ext] # 'import_wizard' (self.setup_io) if is_text_string(load_func): # Import data with import wizard error_message = None try: text, _encoding = encoding.read(self.filename) base_name = osp.basename(self.filename) editor = ImportWizard( self, text, title=base_name, varname=fix_reference_name(base_name)) if editor.exec_(): var_name, clip_data = editor.get_data() self.editor.new_value(var_name, clip_data) except Exception as error: error_message = str(error) else: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() error_message = self.shellwidget.load_data(self.filename, ext) QApplication.restoreOverrideCursor() QApplication.processEvents() if error_message is not None: QMessageBox.critical( self, title, _("<b>Unable to load '%s'</b>" "<br><br>" "The error message was:<br>%s") % (self.filename, error_message)) self.refresh_table()
def _open_overplotted_on(self): item, ok = QInputDialog.getItem(self, "Select Tab", "Tab", self._tab_titles, 0, False) if not ok: return self.open.emit(item, self.entries)