def on_actionLoadTOF_triggered(self): filename = QFileDialog.getOpenFileName( self, 'Open TOF File', '', 'TOF File (*.tof *.TOF);;All files (*)')[0] if filename: self.widget.LoadTofFile(filename) self.add_to_flist(filename, 'tof')
def on_loadTableButton_clicked(self): try: filename = QFileDialog.getOpenFileName( self, 'Open table', osp.expanduser('~') if self.last_save_location is None \ else self.last_save_location, 'Table Files (*.txt *.csv)')[0] if not filename: return headers_from_file, data = import_table_from_csv(filename) if not set(headers_from_file).issubset(set(self.columns_in_order)): raise AttributeError('incorrect headers in file') # Clear existing table before populating from file self.on_clearTableButton_clicked() self._fill_table(headers_from_file, data) for optional in set(headers_from_file).intersection( set(self.optional_columns.keys())): self.optional_columns[optional][1].setChecked(True) except Exception as error: self.showError(f'Could not load {filename}: {error}')
def on_saveTableButton_clicked(self): if self.is_data_in_hidden_columns(): self.showError('Cannot save because data in optional column(s).' 'Select the optional column or clear the column.') return filename = QFileDialog.getSaveFileName( self, 'Save table', osp.expanduser('~') if self.last_save_location is None else self.last_save_location, 'Table files (*.txt *.csv)', initialFilter='*.txt;;*.csv')[0] if not filename: return if not filename.endswith(('.txt', '.csv')): filename = filename + '.csv' self.last_save_location = osp.dirname(filename) try: headers = self._extract_headers_from_table() data = self._extract_data_from_table() export_table_to_csv(data, filename, headers) except Exception as ex: self.showError(f'Cannot write table contents to {filename}:\n{ex}')
def on_buttonBox_clicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.RejectRole: return do_apply = role == QDialogButtonBox.ApplyRole if self.dirty: initialdir = self.client.eval('session.experiment.scriptpath', '') fn = QFileDialog.getSaveFileName(self, 'Save sample file', initialdir, 'Sample files (*.py)')[0] if not fn: return False if not fn.endswith('.py'): fn += '.py' self.filename = fn try: script = self._generate(self.filename) except Exception as err: self.showError('Could not write file: %s' % err) else: if do_apply: self.client.run(script, self.filename) self.showInfo( 'Sample info has been transferred to the daemon.') self.closeWindow()
def selectQSS(self): stylefile = QFileDialog.getOpenFileName(self, filter="Qt Stylesheet Files (" "*.qss)")[0] if stylefile: self.stylefile = stylefile self.setQSS(self.stylefile)
def __init__(self, *args): QFileDialog.__init__(self, *args) self.setAcceptMode(QFileDialog.AcceptOpen) self.setFileMode(QFileDialog.ExistingFiles) self.setOption(QFileDialog.DontUseNativeDialog) filterproxy = FileFilterProxyModel(self) self.setProxyModel(filterproxy) child = None # make pylint happy for child in self.children(): if isinstance(child, QLineEdit): break else: raise NicosError("QLineEdit not found in QFileDialog") child.textChanged.connect(filterproxy.setFilterWildcard) child.returnPressed.disconnect(self.accept) child.returnPressed.connect(self.on_returnPressed)
def savePlot(widget, default_file_type, old_file_path=None): """Saves a plot in the specified file format. :param widget: graphics widget. :param default_file_type: default save file type. :param old_file_path: file path from a previous save operation. :return: returns file path, returns empty string or old file path when user cancels save. """ gr_file_types = {**gr.PRINT_TYPE, **gr.GRAPHIC_TYPE} save_types = ";;".join(sorted(set(gr_file_types.values()))) default_file = 'untitled' if old_file_path: default_file = path.splitext(old_file_path)[0] file_path, _ = QFileDialog.getSaveFileName(None, 'Save as...', default_file, filter=save_types, initialFilter=default_file_type) if not file_path: return "" if not old_file_path else old_file_path file_ext = path.splitext(file_path)[1] if file_ext.lower()[1:] in gr_file_types: widget.save(file_path) else: raise TypeError("Unsupported file format {}".format(file_ext)) return file_path
def saveAs(self): # open a file to save into, create empty output string filepath = QFileDialog.getSaveFileName(self, 'Save as...', path.expanduser('.'), 'Python script (*.py)')[0] if str(filepath): self._save(filepath)
def on_actionLoadPAD_triggered(self): filename = QFileDialog.getOpenFileName(self, 'Open PAD File', '', 'PAD File (*.pad *.PAD);;All files (*)')[0] if filename: self.widget.LoadPadFile(filename) self.updateRange() self.add_to_flist(filename, 'pad')
def loadFile(self): # allows a user to specify the setup file to be parsed setupFile = QFileDialog.getOpenFileName(self, 'Open Python script', path.expanduser('.'), 'Python Files (*.py)')[0] if setupFile: self.readSetupFile(setupFile)
def selectOutputFile(self, ctl, text='Choose an output filename'): previous = ctl.text() if previous: startdir = path.dirname(previous) else: startdir = '.' fn = QFileDialog.getSaveFileName(self, text, startdir, 'All files (*)')[0] if fn: ctl.setText(fn)
def on_actionSave_triggered(self): fn = QFileDialog.getSaveFileName(self, 'Save', '', 'All files (*.*)')[0] if not fn: return try: fn = fn.encode(sys.getfilesystemencoding()) with open(fn, 'w') as f: f.write(self.outView.getOutputString()) except Exception as err: QMessageBox.warning(self, 'Error', 'Writing file failed: %s' % err)
def on_actionOpen_triggered(self): if self.currentEditor is not None and self.filenames[self.currentEditor]: initialdir = path.dirname(self.filenames[self.currentEditor]) else: initialdir = self.client.eval('session.experiment.scriptpath', '') fn = QFileDialog.getOpenFileName(self, 'Open script', initialdir, 'Script files (*.py *.txt)')[0] if not fn: return self.openFile(fn) self.addToRecentf(fn)
def on_saveBtn_clicked(self): initialdir = self.client.eval('session.experiment.proposalpath', '') fn = QFileDialog.getSaveFileName(self, 'Save protocol', initialdir, 'Text files (*.txt)')[0] if not fn: return try: text = self.outText.toPlainText() with open(fn, 'wb') as fp: fp.write(to_utf8(text)) except Exception as err: self.showError('Could not save: %s' % err)
def __init__(self, viewplot, curvenames, *args): QFileDialog.__init__(self, viewplot, *args) self.setOption(self.DontConfirmOverwrite, False) # allow adding some own widgets self.setOption(self.DontUseNativeDialog, True) self.setAcceptMode(QFileDialog.AcceptSave) layout = self.layout() layout.addWidget(QLabel('Curve:', self), 4, 0) self.curveCombo = QComboBox(self) if len(curvenames) > 1: self.curveCombo.addItem('all (in separate files)') self.curveCombo.addItem('all (in one file, multiple data columns)') self.curveCombo.addItems(curvenames) layout.addWidget(self.curveCombo, 4, 1) layout.addWidget(QLabel('Time format:', self), 5, 0) self.formatCombo = QComboBox(self) self.formatCombo.addItems([ 'Seconds since first datapoint', 'UNIX timestamp', 'Text timestamp (YYYY-MM-dd.HH:MM:SS)' ]) layout.addWidget(self.formatCombo, 5, 1)
def actionSaveAsSlot(self): # asks the user where to save the current setup to. if self.getCurrentSetupItem() is None: return filepath = QFileDialog.getSaveFileName(self, 'Save as...', getNicosDir(), 'Python script (*.py)')[0] if filepath: if not str(filepath).endswith('.py'): filepath += '.py' self.save(self.getCurrentSetupItem(), filepath)
def on_script_path_button_clicked(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec_() == QDialog.Accepted: scriptpath = dialog.selectedFiles()[0] self.client.run(f'Exp.scriptpath = "{scriptpath}"') self.scriptPathLine.setText(scriptpath)
def on_saveBtn_clicked(self): initial_dir = self.client.eval('session.experiment.scriptpath', '') filename = QFileDialog.getSaveFileName(self, 'Save sample file', initial_dir, 'Sample files (*.py)')[0] if not filename: return False if not filename.endswith('.py'): filename += '.py' try: self._save_script(filename, self._generate_script()) except Exception as err: self.showError(f'Could not write file: {err}')
def on_actionWriteXml_triggered(self): pad = self.widget.GetPad() if pad is None: return self.showError('No 2-d image is shown.') filename = str(QFileDialog.getSaveFileName( self, 'Select file name', '', 'XML files (*.xml)')[0]) if not filename: return if not filename.endswith('.xml'): filename += '.xml' if TmpImage: tmpimg = TmpImage() tmpimg.ConvertPAD(pad) tmpimg.WriteXML(filename)
def saveFileAs(self, editor): if self.filenames[editor]: initialdir = path.dirname(self.filenames[editor]) else: initialdir = self.client.eval('session.experiment.scriptpath', '') if self.client.eval('session.spMode', False): defaultext = '.txt' flt = 'Script files (*.txt *.py)' else: defaultext = '.py' flt = 'Script files (*.py *.txt)' fn = QFileDialog.getSaveFileName(self, 'Save script', initialdir, flt)[0] if not fn: return False if not fn.endswith(('.py', '.txt')): fn += defaultext self.addToRecentf(fn) self.watchers[editor].removePath(self.filenames[editor]) self.filenames[editor] = fn self.tabber.setTabText(self.editors.index(editor), path.basename(fn)) return self.saveFile(editor)
def on_openFileBtn_clicked(self): initialdir = self.client.eval('session.experiment.scriptpath', '') fn = QFileDialog.getOpenFileName(self, 'Open sample file', initialdir, 'Sample files (*.py)')[0] if not fn: return try: self.configs = parse_sampleconf(fn) except Exception as err: self.showError('Could not read file: %s\n\n' 'Are you sure this is a sample file?' % err) else: self.fileGroup.setEnabled(False) self.sampleGroup.setEnabled(True) newitem = None for config in self.configs: newitem = QListWidgetItem(config['name'], self.list) # select the last item if newitem: self.list.setCurrentItem(newitem) self.on_list_itemClicked(newitem) self.filename = fn
def on_sampleFileBtn_toggled(self, on): if not on: return if not self._init_samplefile: initialdir = self.client.eval('session.experiment.scriptpath', '') fn = QFileDialog.getOpenFileName(self, 'Open sample file', initialdir, 'Sample files (*.py)')[0] if not fn: self.currentSamplesBtn.setChecked(True) return else: fn = self.samplefile try: configs = parse_sampleconf(fn) except Exception as err: self.showError('Could not read file: %s\n\n' 'Are you sure this is a sample file?' % err) self.currentSamplesBtn.setChecked(True) return self.samplefile = fn self.sampleFileLbl.setText(fn) self.sampleFileBtn.setChecked(True) self._reinit(dict(enumerate(configs)))
def selectFileName(self): fn, _ = QFileDialog.getOpenFileName(self, 'Load data points') if fn: self.fileName.setText(fn) self.fileName.editingFinished.emit()
def savePlot(self): saveName = None dialog = QFileDialog(self, "Select file name", "", self._saveTypes) dialog.selectNameFilter(gr.PRINT_TYPE[gr.PRINT_PDF]) dialog.setOption(dialog.HideNameFilterDetails, False) dialog.setAcceptMode(QFileDialog.AcceptSave) if dialog.exec_() == QDialog.Accepted: path = dialog.selectedFiles()[0] if path: _p, suffix = os.path.splitext(path) if suffix: suffix = suffix.lower() else: # append selected name filter suffix (filename extension) nameFilter = dialog.selectedNameFilter() for k, v in gr.PRINT_TYPE.items(): if v == nameFilter: suffix = '.' + k path += suffix break if suffix and (suffix[1:] in gr.PRINT_TYPE or suffix[1:] in gr.GRAPHIC_TYPE): self.save(path) saveName = os.path.basename(path) self._saveName = saveName else: raise Exception("Unsupported file format") return saveName
def selectDirectory(self, ctl, text='Choose a directory'): previous = ctl.text() startdir = previous or '.' fname = QFileDialog.getExistingDirectory(self, text, startdir) if fname: ctl.setText(fname)