Пример #1
0
    def __init__(self, parent):
        QFileDialog.__init__(self, parent)
        self.setFileMode(QFileDialog.AnyFile)
        self.setAcceptMode(QFileDialog.AcceptSave)

        # Widgets
        self._chk_tight = QCheckBox('Tight layout')

        self._txt_dpi = QSpinBox()
        self._txt_dpi.setRange(1, 10000)
        self._txt_dpi.setSingleStep(50)
        self._txt_dpi.setSuffix('dpi')
        self._txt_dpi.setValue(100)

        # Layouts
        layout = self.layout()

        lyt_extras = QHBoxLayout()
        lyt_extras.addWidget(QLabel('Extra options'))
        lyt_extras.addWidget(self._chk_tight)
        lyt_extras.addWidget(QLabel('Resolution'))
        lyt_extras.addWidget(self._txt_dpi)
        layout.addLayout(lyt_extras, layout.rowCount(), 0, 1, layout.columnCount())

        self.setLayout(layout)
Пример #2
0
 def select_manual_output_folder(self):
     # _current_folder = self.main_window.current_folder
     dlg = QFileDialog(parent=self.main_window,
                       caption="Select or Define Output Directory")
     dlg.setFileMode(QFileDialog.Directory)
     if dlg.exec_():
         output_folder_name = str(dlg.selectedFiles()[0])
         self.main_window.autonom_ui.manual_output_folder_field.setText(output_folder_name)
Пример #3
0
    def browse_file(self, type='calibration'):

        if type == 'calibration':
            _current_folder = self.parent.calibration_folder
            _filter = "calib (*.h5);;all (*.*)"
            _caption = "Select Calibration File"
            _output_ui = self.parent.ui.mantid_calibration_value
        else:
            _current_folder = self.parent.characterization_folder
            _filter = "characterization (*-rietveld.txt);;all (*.*)"
            _caption = "Select Characterization File"
            _output_ui = self.parent.ui.mantid_characterization_value

        _file = QFileDialog.getOpenFileName(parent=self.parent,
                                            filter=_filter,
                                            caption=_caption,
                                            directory=_current_folder)
        if not _file:
            return
        if isinstance(_file, tuple):
            _file = _file[0]

        _output_ui.setText(str(_file))
        _path = os.path.dirname(str(_file))

        if type == 'calibration':
            self.parent.calibration_current_folder = _path
        else:
            self.parent.characterization_current_folder = _path
Пример #4
0
 def open_file(self):
     # todo: when more file types are added this should
     # live in its own type
     filepath, _ = QFileDialog.getOpenFileName(self, "Open File...", "", "Python (*.py)")
     if not filepath:
         return
     self.editor.open_file_in_new_tab(filepath)
Пример #5
0
def open_file_dialog(line_edit, filter_text, directory):
    file_name = QFileDialog.getOpenFileName(None, 'Open', directory, filter_text)
    if not file_name:
        return
    if isinstance(file_name, tuple):
        file_name = file_name[0]
    line_edit.setText(file_name)
    def _export(self):
        """
            Exports the current content of the UI to a python script that can
            be run within MantidPlot
        """
        if self._interface is None:
            return

        fname = QFileDialog.getSaveFileName(self, "Mantid Python script - Save script",
                                            self._last_export_directory,
                                            "Python script (*.py)")
        if not fname:
            return

        if isinstance(fname, tuple):
            fname = fname[0]
        fname = str(fname)
        if not fname.endswith('.py'):
            fname += ".py"
        (folder, file_name) = os.path.split(fname)
        self._last_export_directory = folder
        script = self._interface.export(fname)
        if script is not None:
            self.statusBar().showMessage("Saved as %s" % fname)
        else:
            self.statusBar().showMessage("Could not save file")
Пример #7
0
    def do_export_selected_scans(self):
        """
        export selected scans to a file
        :return:
        """
        # get the scans
        scans_list = self._myParent.ub_matrix_processing_table.get_selected_scans()
        scans_list.sort()

        # form the output string
        output_str = '# Exp = {0}.\n'.format(self._myParent.current_exp_number)
        for scan in scans_list:
            output_str += '{0}, '.format(scan)

        # trim the last
        output_str = output_str[:-2]

        # get the output file name
        file_filter = 'Text Files (*.dat);;All Files (*.*)'
        file_name = QFileDialog.getSaveFileName(self, 'File to export selected scans',
                                                self._myParent.working_directory, file_filter)
        if not file_name:
            return
        if isinstance(file_name, tuple):
            file_name = file_name[0]

        # write file
        out_file = open(file_name, 'w')
        out_file.write(output_str)
        out_file.close()
Пример #8
0
 def output_dir_button_clicked(self):
     _output_folder = QFileDialog.getExistingDirectory(caption="Select Output Folder ...",
                                                       directory=self.parent.output_folder,
                                                       options=QFileDialog.ShowDirsOnly)
     if _output_folder:
         self.ui.output_dir_label.setText(str(_output_folder))
         self.parent.output_folder = str(_output_folder)
Пример #9
0
 def cache_dir_button_clicked(self):
     _cache_folder = QFileDialog.getExistingDirectory(caption="Select Cache Folder ...",
                                                      directory=self.parent.cache_folder,
                                                      options=QFileDialog.ShowDirsOnly)
     if _cache_folder:
         self.ui.cache_dir_label.setText(str(_cache_folder))
         self.parent.cache_folder = str(_cache_folder)
Пример #10
0
    def request_config_file_name(self, open_flag=True):
        _caption = 'Select or Define a Configuration File Name'
        _current_folder = self.parent.configuration_folder
        if open_flag:
            _file = QFileDialog.getOpenFileName(parent=self.parent,
                                                filter='config (*.cfg)',
                                                caption=_caption,
                                                directory=_current_folder)
            if isinstance(_file, tuple):
                _file = _file[0]
        else:
            _file, _ = get_save_file(parent=self.parent,
                                     filter={'config (*.cfg)':'cfg'},
                                     caption=_caption,
                                     directory=_current_folder)

        if not _file:
            self.filename = ''
            return

        _new_path = os.path.dirname(_file)
        self.parent.configuration_folder = _new_path
        o_file_handler = FileHandler(filename=_file)
        o_file_handler.check_file_extension(ext_requested='cfg')
        self.filename = o_file_handler.filename
    def _save_as(self):
        """
            Present a file dialog to the user and saves the content of
            the UI in XML format.
        """
        if self._filename is not None:
            fname = self._filename
        else:
            fname = self._instrument + '_'

        fname = QFileDialog.getSaveFileName(self, "Reduction settings - Save settings",
                                            self._last_directory + '/' + fname,
                                            "Settings files (*.xml)")
        if not fname:
            return

        if isinstance(fname, tuple):
            fname = fname[0]
        fname = str(QFileInfo(fname).filePath())
        if not fname.endswith('.xml'):
            fname += ".xml"
        if fname in self._recent_files:
            self._recent_files.remove(fname)
        self._recent_files.insert(0,fname)
        while len(self._recent_files) > 10:
            self._recent_files.pop()
        self._last_directory = QFileInfo(fname).path()
        self._filename = fname
        self._save()
Пример #12
0
 def hough_load_btn(self):
     try:
         options = QFileDialog.Options()
         self.hough_fileName, _ = QFileDialog.getOpenFileName(
             None,
             'Upload Image',
             '',
             '*.png *.jpg *.jpeg',
             options=options)
         pixmap = QPixmap(self.hough_fileName)
         if (not pixmap.isNull()):
             pixmap = pixmap.scaled(self.label_hough_in.width(),
                                    self.label_hough_in.height(),
                                    QtCore.Qt.KeepAspectRatio)
             self.label_hough_in.setPixmap(pixmap)
     except Exception as err:
         print(err)
Пример #13
0
 def open_file(self):
     # todo: when more file types are added this should
     # live in its own type
     filepath, _ = QFileDialog.getOpenFileName(self, "Open File...", "",
                                               "Python (*.py)")
     if not filepath:
         return
     self.editor.open_file_in_new_tab(filepath)
Пример #14
0
 def export_file(self, f, text, ffilter="*"):
     """Export to file."""
     fname = QFileDialog.getSaveFileName(self, text, filter=ffilter)[0]
     if fname:
         try:
             f(fname, ffilter)
         except TypeError:
             f(fname)
Пример #15
0
    def ButExportDCClick(self):
        self.GetDataFromDb(DC=True)

        fileName, _ = QFileDialog.getSaveFileName(
            self, "Export Data", "", "Pickle Files (*.pkl);;All Files (*)")
        ExptData = {}
        ExptData['DataDC'] = (self.DataDC)
        pickle.dump(ExptData, open(fileName, 'wb'))
Пример #16
0
 def grouping_button(self, key=None, grouping_type='input'):
     message = "Select {} grouping".format(grouping_type)
     ext = 'Grouping (*.txt);;All (*.*)'
     file_name = QFileDialog.getOpenFileName(
         self.main_window, message, self.main_window.calibration_folder,
         ext)
     if file_name is None:
         return
Пример #17
0
def open_file_dialog(line_edit, filter_text, directory):
    file_name = QFileDialog.getOpenFileName(None, 'Open', directory,
                                            filter_text)
    if not file_name:
        return
    if isinstance(file_name, tuple):
        file_name = file_name[0]
    line_edit.setText(file_name)
Пример #18
0
    def sift_imgB_load(self):
        try:
            options = QFileDialog.Options()
            self.siftB, _ = QFileDialog.getOpenFileName(None,
                                                        'Upload Image',
                                                        '',
                                                        '*.png *.jpg *.jpeg',
                                                        options=options)
            pixmap = QPixmap(self.siftB)
            if (not pixmap.isNull()):
                pixmap = pixmap.scaled(self.label_input_SIFT_B.width(),
                                       self.label_input_SIFT_B.height(),
                                       QtCore.Qt.KeepAspectRatio)
                self.label_input_SIFT_B.setPixmap(pixmap)

        except Exception as err:
            print(err)
    def browse_file(self):

        response = QFileDialog.getOpenFileName(self, 'Open Image File')
        self.file_address = response[0]
        if not os.path.exists(self.file_address):
            return
        # return
        self.process_file()
Пример #20
0
 def _open_images(self):
     """Adds image files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select image(s)...',
         directory=self._last_visited_dir,  # home dir by default
     )
     self._add_files(filenames)
Пример #21
0
 def save_state_dialogue(self):
     filename = QFileDialog.getSaveFileName(self, 'Save state',
                                            self.last_state_folder,
                                            "Text documents (*.txt)")[0]
     if filename != '':
         self.save_state(filename)
         self.last_state_folder = os.path.dirname(filename)
         print(self.last_state_folder)
Пример #22
0
    def _on_load_from_file(self):
        filename = QFileDialog.getOpenFileName(
            self, caption='Load Model',
            filter=SPECVIZ_MODEL_FILE_FILTER)[0]
        if not filename:
            return

        self._load_model_from_file(filename)
Пример #23
0
 def selectFile(self):
     self.__reinit_fields()
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.ExistingFile)
     dialog.setWindowTitle('Select Audio or Video File')
     if dialog.exec():
         selected = dialog.selectedFiles()
         if len(selected) > 0:
             self.inputFile.setText(selected[0])
             self.__probe_file()
Пример #24
0
 def showBeqDirectoryPicker(self):
     ''' selects an output directory for the beq files '''
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.DirectoryOnly)
     dialog.setWindowTitle(f"Select BEQ Files Download Directory")
     if dialog.exec():
         selected = dialog.selectedFiles()
         if len(selected) > 0:
             self.beqFiltersDir.setText(selected[0])
             self.__count_beq_files()
Пример #25
0
def openfilecheck(open_mode, file_name='', file_ext='', file_type=''):
    """
    :param open_mode: {str} method to open the file (e.g., 'rb' for binary read only)
    :param file_name: [optional] {str} full path of file to open
    :param file_ext:  [optional] {str} file extension (e.g., '.nev')
    :param file_type: [optional] {str} file type for use when browsing for file (e.g., 'Blackrock NEV Files')
    :return: {file} opened file
    """

    while True:
        if not file_name:  # no file name passed

            # Ask user to specify a file path or browse
            file_name = input("Enter complete " + file_ext +
                              " file path or hit enter to browse: ")

            if not file_name:
                if 'app' not in locals(): app = QApplication([])
                if not file_ext: file_type = 'All Files'
                file_name = QFileDialog.getOpenFileName(
                    QFileDialog(), "Select File", getcwd(),
                    file_type + " (*" + file_ext + ")")

        # Ensure file exists (really needed for users type entering)
        if path.isfile(file_name):
            # Ensure given file matches file_ext
            if file_ext:
                _, fext = path.splitext(file_name)

                # check for * in extension
                if file_ext[-1] == '*': test_extension = file_ext[:-1]
                else: test_extension = file_ext

                if fext[0:len(test_extension)] != test_extension:
                    file_name = ''
                    print("\n*** File given is not a " + file_ext +
                          " file, try again ***\n")
                    continue
            break
        else:
            file_name = ''
            print("\n*** File given does exist, try again ***\n")

    print('\n' + file_name.split('/')[-1] + ' opened')
    return open(file_name, open_mode)
Пример #26
0
 def grouping_button(self, key=None, grouping_type='input'):
     message = "Select {} grouping".format(grouping_type)
     ext = 'Grouping (*.txt);;All (*.*)'
     file_name = QFileDialog.getOpenFileName(self.main_window,
                                             message,
                                             self.main_window.calibration_folder,
                                             ext)
     if file_name is None:
         return
Пример #27
0
 def _open_folder(self):
     """Add a folder of files from the menubar."""
     folder = QFileDialog.getExistingDirectory(
         parent=self,
         caption='Select folder...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if folder is not None:
         self._add_files([folder])
Пример #28
0
 def pb_load_mask_clicked(self):
     dir_name = self._compute_home_directory()
     file_name = QFileDialog.getOpenFileName(self, "Load Mask From File",
                                             dir_name, "All (*)")
     file_name = file_name[0]
     if file_name:
         self._mask_file_path = file_name
         self._show_mask_file_path()
         logger.debug(f"Mask file is selected: '{file_name}'")
Пример #29
0
 def input_from_multiple(self, format_name: str,
                         format_choose: Sequence[str]) -> List[str]:
     """Get external file names."""
     file_names, suffix = QFileDialog.getOpenFileNames(
         self, f"Open {format_name} files ...", self.env,
         ';;'.join(format_choose))
     if file_names:
         self.set_locate(QFileInfo(file_names[0]).absolutePath())
     return file_names
Пример #30
0
 def __set_dir(self) -> None:
     """Choose path and it will be set as environment variable if accepted."""
     path = self.path_edit.text()
     if not isdir(path):
         path = self.path_edit.placeholderText()
     path = QFileDialog.getExistingDirectory(self, "Choose a directory",
                                             path)
     if path:
         self.path_edit.setText(path)
Пример #31
0
 def _open_files_dialog_as_stack_dialog(self):
     """Add files as a stack, from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select files...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.open(filenames, stack=True)
    def import_spectrum(self):
        self.statusBar().showMessage("Import spectrum", 2000)

        path = os.path.dirname(__file__)
        formats = ["*.msa", "*.txt"]
        file_filters = "Spectrum file ({:s})".format(" ".join(formats))
        file_names = QFileDialog.getOpenFileName(self,
                                                 "Import an x-ray spectrum",
                                                 path, file_filters)
Пример #33
0
def load_filter(parent, status_bar=None):
    '''
    Presents a file dialog to the user so they can choose a filter to load.
    :return: the loaded filter, if any.
    '''
    dialog = QFileDialog(parent=parent)
    dialog.setFileMode(QFileDialog.ExistingFile)
    dialog.setNameFilter(f"*.filter")
    dialog.setWindowTitle(f"Load Filter")
    if dialog.exec():
        selected = dialog.selectedFiles()
        if len(selected) > 0:
            with open(selected[0], 'r') as infile:
                input = json.load(infile)
                if status_bar is not None:
                    status_bar.showMessage(f"Loaded filter from {infile.name}")
                return input
    return None
Пример #34
0
 def _open_folder_dialog(self):
     """Add a folder of files from the menubar."""
     folder = QFileDialog.getExistingDirectory(
         parent=self,
         caption='Select folder...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if folder not in {'', None}:
         self.viewer.open([folder])
Пример #35
0
 def dir_browse_dialog(self, title: str = 'Select Directory') -> str:
     r"""Pop up a directory dialog box.
     @param title: string to use as dialog's title
     @returns absolute path to directory
     """
     dirname = QFileDialog.getExistingDirectory(self, caption=title)
     if isinstance(dirname, tuple):
         dirname = dirname[0]
     return dirname
Пример #36
0
 def pick_user_source_dir(self):
     '''
     Sets the user source directory.
     '''
     dialog = QFileDialog(parent=self)
     dialog.setFileMode(QFileDialog.DirectoryOnly)
     dialog.setOption(QFileDialog.ShowDirsOnly)
     dialog.setWindowTitle('Choose a directory which holds your own BEQ files')
     if dialog.exec():
         selected = dialog.selectedFiles()
         if len(selected) > 0:
             if os.path.abspath(selected[0]) == os.path.abspath(self.__beq_dir):
                 QMessageBox.critical(self, '',
                                      f"User directory cannot be inside the input directory, choose a different folder",
                                      QMessageBox.Ok)
             else:
                 self.userSourceDir.setText(selected[0])
                 self.update_beq_count()
Пример #37
0
 def master_browse_button_clicked(self):
     _master_folder = QFileDialog.getExistingDirectory(
         caption="Select Output Folder ...",
         directory=self.parent.output_folder,
         options=QFileDialog.ShowDirsOnly)
     if _master_folder:
         self.ui.master_output_directory_label.setText(str(_master_folder))
         self.master_folder = _master_folder
         self.check_run_calibration_status()
Пример #38
0
 def _open_files_dialog(self):
     """Add files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption=trans._('Select file(s)...'),
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.open(filenames)
Пример #39
0
 def _save_particles(self):
     """Callback called when save particles button is clicked"""
     file = QFileDialog.getSaveFileName(self, 'Save File')
     if len(file) > 0:
         layer = self.viewer.layers[self._particles_layers.currentText()]
         particles = SParticles(data=layer.data,
                                properties=layer.properties,
                                scale=layer.scale)
         write_particles(file[0], particles)
Пример #40
0
 def _open_images(self):
     """Add image files from the menubar."""
     filenames, _ = QFileDialog.getOpenFileNames(
         parent=self,
         caption='Select image(s)...',
         directory=self._last_visited_dir,  # home dir by default
     )
     if (filenames != []) and (filenames is not None):
         self.viewer.add_path(filenames)
Пример #41
0
 def handle_import_data_btn_clicked(self):
     open_file_info = QFileDialog.getOpenFileName(self,
                                                  caption="Save File",
                                                  filter="*." +
                                                  IMPORT_FILE_FORMAT)
     open_file_name = open_file_info[0]
     if open_file_name:
         importer = SettingsImporter(self)
         importer.import_settings(open_file_name)
Пример #42
0
 def importFile(self):
     options = QFileDialog.Options()
     filename, filtr = QFileDialog.getOpenFileName(
         self, config.thisTranslation["import"],
         config.thisTranslation["liveFilter"], "File (*.*)", "", options)
     if filename:
         try:
             with open(filename, errors='ignore') as f:
                 for line in f:
                     data = line.split(":::")
                     filter = data[0].strip()
                     pattern = data[1].strip()
                     if self.db.checkFilterExists(filter):
                         self.db.delete(filter)
                     self.db.insert(filter, pattern)
         except Exception as e:
             print(e)
         self.reloadFilters()
Пример #43
0
def browse_calibration_clicked(main_window):
    _calibration_folder = main_window.calibration_folder
    [_calibration_file,
     _] = QFileDialog.getOpenFileName(parent=main_window,
                                      caption="Select Calibration File",
                                      directory=_calibration_folder,
                                      filter=main_window.calibration_extension)
    if _calibration_file:
        main_window.processing_ui.calibration_file.setText(_calibration_file)
Пример #44
0
 def _savedir_browse(self):
     save_dir = QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory",
                                                       os.path.expanduser('~'),
                                                       QFileDialog.ShowDirsOnly
                                                       | QFileDialog.DontResolveSymlinks)
     if not save_dir:
         return
     if isinstance(save_dir, tuple):
         save_dir = save_dir[0]
     self._content.savedir_edit.setText(save_dir)
Пример #45
0
 def get_directory_name_for_saving(self):
     """
     Pops up a directory selection dialogue
     :return : The path to the directory
     """
     # Note that the native dialog does not always show the files
     # in the directory on Linux, but using the non-native dialog
     # is not very pleasant on Windows or Mac
     directory = QFileDialog.getExistingDirectory(caption='Select folder for exported plots')
     return directory
Пример #46
0
 def saveText(self):
     """
     Saves the generated text to a file (opens file dialog).
     """
     fname = QFileDialog.getSaveFileName(self, 'Open file', '')
     if isinstance(fname, tuple):
         fname = fname[0]
     fid = open(fname, 'w')
     fid.write(self.genText())
     fid.close()
Пример #47
0
    def show_savecfg_dlg(self):
        filename, _ = QFileDialog.getSaveFileName(
            self, self.tr("Save configuration file..."),
            directory=os.path.expanduser("~"),
            filter="Json file (*.json)"
        )

        if filename:
            self.filename = filename
            self.save_file()
Пример #48
0
 def target_autonom_clicked(self):
     _autonom_folder = QFileDialog.getExistingDirectory(caption="Select Output autoNOM Folder ...",
                                                        directory=self.parent.current_folder,
                                                        options=QFileDialog.ShowDirsOnly)
     if not _autonom_folder:
         return
     if isinstance(_autonom_folder, tuple):
         _autonom_folder = _autonom_folder[0]
     _autonom_folder = os.path.basename(_autonom_folder)
     self.ui.target_autonom_value.setText(str(_autonom_folder))
     self.check_status_transfer_button()
Пример #49
0
    def browse_File(self):
        """ Open a file dialog to get file
        """
        filename = QFileDialog.getOpenFileName(self, 'Input File Dialog',
                                               self._defaultdir, "Data (*.nxs *.dat);;All files (*)")
        if isinstance(filename, tuple):
            filename = filename[0]

        self.ui.lineEdit.setText(filename)

        Logger("Filter_Events").information('Selected file: "{}"'.format(filename))
Пример #50
0
    def show_opencfg_dlg(self):
        # show file dialog
        filename, _ = QFileDialog.getOpenFileName(
            self, self.tr("Open configuration file..."),
            directory=os.path.expanduser("~"),
            filter=self.tr("Json file (*.json);;All files (*.*)")
        )

        # load config file
        if filename:
            self.load_file(filename)
Пример #51
0
 def _output_dir_browse(self):
     output_dir = QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory",
                                                         os.path.expanduser('~'),
                                                         QFileDialog.ShowDirsOnly
                                                         | QFileDialog.DontResolveSymlinks)
     if not output_dir:
         return
     if isinstance(output_dir, tuple):
         output_dir = output_dir[0]
     self._summary.output_dir_edit.setText(output_dir)
     self._settings.emit_key_value("OUTPUT_DIR", output_dir)
Пример #52
0
 def get_file_name_for_saving(self, extension):
     """
     Pops up a file selection dialog with the filter set to the
     extension type
     :param extension: The file extension to use which defines the
                       export type
     :return absolute_path: The absolute path to save to
     """
     # Returns a tuple containing the filename and extension
     absolute_path = QFileDialog.getSaveFileName(caption='Select filename for exported plot',
                                                 filter='*{}'.format(extension))
     return absolute_path[0]
Пример #53
0
    def dir_browse_dialog(self):
        """
            Pop up a directory dialog box.
            @param data_type: string used to filter the files
            @param title: string to use as title
            @param multi: multiselection is enabled if True
        """
        dirname = QFileDialog.getExistingDirectory(self, "Select Directory")
        if isinstance(dirname, tuple):
            dirname = dirname[0]

        return dirname
Пример #54
0
 def move_to_folder(self):
     _new_folder = QFileDialog.getExistingDirectory(parent=self.main_window,
                                                    caption="Select working directory",
                                                    directory=self.current_folder)
     if not _new_folder:
         self.user_canceled = True
     else:
         if isinstance(_new_folder, tuple):
             _new_folder = _new_folder[0]
         os.chdir(_new_folder)
         self.main_window.current_folder = _new_folder
         self.main_window.setWindowTitle(_new_folder)
Пример #55
0
def _writeToFile(out_model_dict, model_directory, parent):

    fname = QFileDialog.getSaveFileName(parent, 'Save to file', model_directory)[0]

    if len(fname) > 0:
        # enforce correct suffix.
        if not fname.endswith(".yaml"):
            fname += ".yaml"

        f = open(fname, "w")
        yaml.dump(out_model_dict, f,default_flow_style=False)
        f.close()
Пример #56
0
def get_save_file(parent, directory=None, caption=None, filter=dict()):
    '''
    This is operating under the assumption that the file_filters parameter is a dict of filter:extension

    The filename will have the file extension appended if one isn't already found on it

    It returns a pair (<filename with extension>, <extension>). In the case of user cancelling, the filename
    returned is None
    '''
    # convert defaults into something useful
    if not directory:
        # try to get it from the parent
        if parent:
            try:
                directory = parent._currWorkDir
            except:
                pass
        # just give up and use the current working directory
        if not directory:
            directory = os.getcwd()

    if not caption:
        caption = 'Save File'

    if filter:
        dialogfilter = ';;'.join(filter.keys())
    else:
        dialogfilter = ''

    result = QFileDialog.getSaveFileName(parent=parent, directory=directory, caption=caption,
                                         filter=dialogfilter)

    # qt4/qt5 return slightly different things
    if isinstance(result, tuple):
        filename, filefilter = result
    else:
        filename = result
        filefilter = None

    # check if the user canceled
    if not filename:
        return None, filefilter

    # determine the type and add the extension
    extension = os.path.splitext(str(filename))[-1]
    filetype = filter.get(filefilter, None)
    if filetype is None:
        filetype = extension.replace('.', '')
    elif not extension:
        # implementation ties filetype to the extension
        filename = '{}.{}'.format(filename, filetype)

    return filename, filetype
Пример #57
0
    def load_tool(self, checked):
        try:
            curr_dir = os.path.dirname(self.current_file())
        except IndexError:
            logger.error("The display manager does not have a display loaded. Suggesting current work directory.")
            curr_dir = os.getcwd()
        filename = QFileDialog.getOpenFileName(self, 'Load tool...', curr_dir, 'PyDM External Tool Files (*_tool.py)')
        filename = filename[0] if isinstance(filename, (list, tuple)) else filename

        if filename:
            filename = str(filename)
            tools.install_external_tool(filename)
            self.update_tools_menu()
Пример #58
0
    def browse_folder(self):
        _current_folder = self.current_folder
        _caption = "Select Output Folder"

        _folder = QFileDialog.getExistingDirectory(parent=self.parent,
                                                   caption=_caption,
                                                   directory=_current_folder)
        if not _folder:
            return
        if isinstance(_folder, tuple):
            _folder = _folder[0]

        self.parent.ui.mantid_output_directory_value.setText(str(_folder) + self._output_ext)
Пример #59
0
 def source_ipts_clicked(self):
     _ipts_folder = QFileDialog.getExistingDirectory(caption="Select Input IPTS Folder ...",
                                                     directory=self.ipts_folder,
                                                     options=QFileDialog.ShowDirsOnly)
     if not _ipts_folder:
         return
     if isinstance(_ipts_folder, tuple):
         _ipts_folder = _ipts_folder[0]
     self.ipts_folder = _ipts_folder
     _ipts_folder = os.path.basename(_ipts_folder)
     _ipts_number = _ipts_folder.split('-')[1]
     self.ui.source_ipts_value.setText(str(_ipts_number))
     self.check_status_transfer_button()
Пример #60
0
def _writeToFile(expression_string, model_directory, parent, header):

    fname = QFileDialog.getSaveFileName(parent, 'Export to .py file', model_directory)[0]

    if len(fname) > 0:
        # enforce correct suffix.
        if not fname.endswith(".py"):
            fname += ".py"

        f = open(fname, 'w')

        f.write(header)
        f.write(expression_string)
        f.close()