我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用PyQt5.QtWidgets.QFileDialog()。
def createTorrent(self): if os.path.isfile(self.inputEdit.text()): save_fn = os.path.splitext( os.path.split(self.inputEdit.text())[1])[0] + '.torrent' else: save_fn = self.inputEdit.text().split(os.sep)[-1] + '.torrent' if self.last_output_dir and os.path.exists(self.last_output_dir): save_fn = os.path.join(self.last_output_dir, save_fn) fn = QtWidgets.QFileDialog.getSaveFileName( self.MainWindow, 'Save torrent', save_fn, filter=('Torrent file (*.torrent)'))[0] if fn: self.last_output_dir = os.path.split(fn)[0] self.creation_thread = CreateTorrentQThread( self.torrent, fn) self.creation_thread.started.connect( self.creation_started) self.creation_thread.progress_update.connect( self._progress_update) self.creation_thread.finished.connect( self.creation_finished) self.creation_thread.onError.connect( self._showError) self.creation_thread.start()
def save_dialog(self): try: save_dialog = QtWidgets.QFileDialog() save_dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) file_path = save_dialog.getSaveFileName(self, 'Save as... File', './', filter='All Files(*.*);; Text Files(*.txt)') if file_path[0]: self.file_path = file_path file_open = open(self.file_path[0], 'w') self.file_name = (self.file_path[0].split('/'))[-1] self.statusBar().showMessage('Saved at: {}'.format(self.file_path[0])) self.setWindowTitle("{} - Notepad".format(self.file_name)) with file_open: file_open.write(self.text_widget.toPlainText()) self.need_saving(False) except FileNotFoundError as why: self.error_box(why) pass
def export_profile(self): fn = QtWidgets.QFileDialog.getSaveFileName( self.MainWindow, 'Save profile', self.last_output_dir, filter=('JSON configuration file (*.json)'))[0] if fn: exclude = self.excludeEdit.toPlainText().strip().splitlines() trackers = self.trackerEdit.toPlainText().strip().split() web_seeds = self.webSeedEdit.toPlainText().strip().split() private = self.privateTorrentCheckBox.isChecked() compute_md5 = self.md5CheckBox.isChecked() source = self.sourceEdit.text() data = { 'exclude': exclude, 'trackers': trackers, 'web_seeds': web_seeds, 'private': private, 'compute_md5': compute_md5, 'source': source } with open(fn, 'w') as f: json.dump(data, f, indent=4, sort_keys=True) self._statusBarMsg("Profile saved to " + fn)
def import_profile(self): fn = QtWidgets.QFileDialog.getOpenFileName( self.MainWindow, 'Open profile', self.last_input_dir, filter=('JSON configuration file (*.json)'))[0] if fn: with open(fn) as f: data = json.load(f) exclude = data.get('exclude', []) trackers = data.get('trackers', []) web_seeds = data.get('web_seeds', []) private = data.get('private', False) compute_md5 = data.get('compute_md5', False) source = data.get('source', '') try: self.excludeEdit.setPlainText(os.linesep.join(exclude)) self.trackerEdit.setPlainText(os.linesep.join(trackers)) self.webSeedEdit.setPlainText(os.linesep.join(web_seeds)) self.privateTorrentCheckBox.setChecked(private) self.md5CheckBox.setChecked(compute_md5) self.sourceEdit.setText(source) except Exception as e: self._showError(str(e)) return self._statusBarMsg("Profile {} loaded".format( os.path.split(fn)[1]))
def pickExecutable( parent, executable ): file_browser = QtWidgets.QFileDialog( parent ) file_browser.setFileMode( file_browser.ExistingFile ) file_browser.setOption( file_browser.ReadOnly, True ) file_browser.setOption( file_browser.DontResolveSymlinks, True ) file_browser.setViewMode( file_browser.Detail ) # Without Readable will not return a Executable image file_browser.setFilter( QtCore.QDir.Files|QtCore.QDir.Executable|QtCore.QDir.Readable ) if executable is not None and executable.name != '': file_browser.setDirectory( str( executable.parent ) ) file_browser.selectFile( str( executable.name ) ) else: file_browser.setDirectory( str(wb_platform_specific.getDefaultExecutableFolder()) ) if file_browser.exec_(): all_files = file_browser.selectedFiles() assert len(all_files) == 1 return all_files[0] else: return None
def _select_file(self): graphical_image_filters = [' '.join(el) for el in self._extension_filters] + ['All files (*)'] open_file, used_filter = QFileDialog().getSaveFileName(caption='Select the output file', filter=';;'.join(graphical_image_filters)) if not any(open_file.endswith(el[0]) for el in self._extension_filters): extension_from_filter = list(filter(lambda v: ' '.join(v) == used_filter, self._extension_filters)) if extension_from_filter: extension = extension_from_filter[0][0] else: extension = self._extension_filters[0][0] open_file += '.{}'.format(extension) if open_file: self.outputFile_box.setText(open_file) self._update_ok_button()
def csv_import_fnc(self, _): """ Open a CsvImportWindow """ if self.try_locking("notes_management"): self._close_window() path, _ = QtWidgets.QFileDialog().getOpenFileName( self, "Imported", "", "CSV Files (*.csv)" ) if path: try: self.cur_window = CsvImportWindow(path) self._connect_window("notes_management") except csv.Error: api.redis.unlock("notes_management") else: api.redis.unlock("notes_management")
def _save_visualization(self): current_tab = self._tabs[self.ui.tabWidget.currentIndex()] if isinstance(current_tab, PreprocessorController): return dialog = QtWidgets.QFileDialog(self) dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setNameFilters(["Processed data file (*.p)", "All Files (*)"]) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setDefaultSuffix(".p") dialog.exec() fname = dialog.selectedFiles()[0] success = current_tab.save_data(fname) if not success: QtWidgets.QMessageBox.about(self, "Save Error", "An error occured saving the file\nCheck the log for more details")
def path_button_clicked(self): """ Called when the user clicks the button next to the line edit - the path choosing button. First checks if there is text in the line edit and uses that for the initial search directory. If not, then it defaults to the user $HOME directory. Once a directory is chosen and the user has not clicked cancel (cancel returns an empty path) it directly sets the line edit text. """ open_dialog = QFileDialog() if not self.path_text.text(): button_path = expanduser("~") else: button_path = self.path_text.text() temp_path = open_dialog.getExistingDirectory(self, "Package directory:", button_path) if temp_path: self.path_text.setText(temp_path)
def open_dialog(self): """ Open 'Open Dialog Box' """ if self.has_changed: self.save_box(open=True) try: self.file_path = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', './', filter="All Files(*.*);;Text Files(*.txt)") if self.file_path[0]: self.file_name = (self.file_path[0].split('/'))[-1] self.setWindowTitle("{} - Notepad".format(self.file_name)) file_open = open(self.file_path[0], 'r+') self.statusBar().showMessage('Open... {}'.format(self.file_path[0])) with file_open: content = file_open.read() self.text_widget.setPlainText(content) self.need_saving(False) except UnicodeDecodeError as why: self.error_box(why) pass
def browseInput(self): qfd = QtWidgets.QFileDialog(self.MainWindow) if self.last_input_dir and os.path.exists(self.last_input_dir): qfd.setDirectory(self.last_input_dir) if self.inputMode == 'file': qfd.setWindowTitle('Select file') qfd.setFileMode(QtWidgets.QFileDialog.ExistingFile) else: qfd.setWindowTitle('Select directory') qfd.setFileMode(QtWidgets.QFileDialog.Directory) if qfd.exec_(): fn = qfd.selectedFiles()[0] self.inputEdit.setText(fn) self.last_input_dir = os.path.split(fn)[0] self.initializeTorrent()
def createTorrentBatch(self): save_dir = QtWidgets.QFileDialog.getExistingDirectory( self.MainWindow, 'Select output directory', self.last_output_dir) if save_dir: self.last_output_dir = save_dir trackers = self.trackerEdit.toPlainText().strip().split() web_seeds = self.webSeedEdit.toPlainText().strip().split() self.creation_thread = CreateTorrentBatchQThread( path=self.inputEdit.text(), exclude=self.excludeEdit.toPlainText().strip().splitlines(), save_dir=save_dir, trackers=trackers, web_seeds=web_seeds, private=self.privateTorrentCheckBox.isChecked(), source=self.sourceEdit.text(), comment=self.commentEdit.text(), include_md5=self.md5CheckBox.isChecked(), ) self.creation_thread.started.connect( self.creation_started) self.creation_thread.progress_update.connect( self._progress_update_batch) self.creation_thread.finished.connect( self.creation_finished) self.creation_thread.onError.connect( self._showError) self.creation_thread.start()
def select_bw2_dir_path(self): folder_path = QtWidgets.QFileDialog().getExistingDirectory( None, "Select a brightway2 database folder") # TODO: in case of a directory that does not contain an existing brightway2 database, # ask if a new db should be set up print(folder_path) self.switch_brightway2_dir_path(folder_path) return folder_path
def _on_select_path_file(self): path = QFileDialog().getOpenFileName(self, 'Add file path to be served by the file server', os.path.expanduser('~')) self._path_bar.setCurrentText(path[0])
def _on_select_path_directory(self): path = QFileDialog().getExistingDirectory(self, 'Add directory lookup path for the file server', os.path.expanduser('~')) self._path_bar.setCurrentText(path)
def pickFolder( parent, orig_folder ): if orig_folder is None or orig_folder == '.': orig_folder = wb_platform_specific.getHomeFolder() folder = orig_folder if folder.exists(): if not folder.is_dir(): folder = folder.parent else: while not orig_folder.exists(): orig_folder = orig_folder.parent file_browser = QtWidgets.QFileDialog( parent ) file_browser.setFileMode( file_browser.Directory ) # # When ShowDirsOnly is True QFileDialog show a number of # bugs: # 1. folder double click edits folder name # 2. setDirectory does not work, always starts in $HOME # file_browser.setOption( file_browser.ShowDirsOnly, False ) file_browser.setOption( file_browser.ReadOnly, True ) file_browser.setViewMode( file_browser.Detail ) file_browser.setFilter( QtCore.QDir.Hidden | QtCore.QDir.Dirs ) file_browser.setDirectory( str( folder ) ) file_browser.selectFile( str( orig_folder ) ) if file_browser.exec_(): all_directories = file_browser.selectedFiles() assert len(all_directories) == 1 return pathlib.Path( all_directories[0] ) return None
def browse_paired_file(self): self.dialog = QW.QFileDialog(self) file_path = self.dialog.getOpenFileNames(self, "Select a sample", ".", self.filter)[0] if not file_path: self.set_empty_path() elif len(file_path) > 2: msg = WarningMessage("You must pick only one sample (1 or 2 files)", self) self.set_empty_path() msg.exec_() else: self._set_paired_filenames(file_path)
def browse_file(self): try: # Set the default path to the previous choice if self.paths: default = self.paths else: default = "." file_path = QW.QFileDialog.getOpenFileNames(self, "Single File", default, self.filter)[0][0] self.set_filenames(file_path) except IndexError: self.set_empty_path()
def __init__(self, parent, title, directory, file_filter): super().__init__(parent) self.setAcceptMode(QW.QFileDialog.AcceptOpen) self.setFileMode(QW.QFileDialog.Directory) self.setViewMode(QW.QFileDialog.Detail) self.setWindowTitle(title) self.setDirectory(directory) self.setNameFilter(file_filter)
def _set_qdialog_basedir(self): if not self._qdialog_basedir_set: data = self._controller.get_model().get_data() for map_name, file_path in data.get_file_paths().items(): if file_path: QFileDialog().setDirectory(file_path) self._qdialog_basedir_set = True return
def _add_new_files(self): new_files = QFileDialog(self).getOpenFileNames(caption='Nifti files', filter=';;'.join(image_files_filters)) if new_files[0]: self._add_new_maps(new_files[0])
def _save_settings(self): """Save the current settings as a text file. Args: file_name: the filename to write to """ current_model = self._controller.get_model() config_file = ['conf (*.conf)', 'All files (*)'] file_name, used_filter = QFileDialog().getSaveFileName(caption='Select the GUI config file', filter=';;'.join(config_file)) if file_name: with open(file_name, 'w') as f: f.write(current_model.get_config().to_yaml())
def _load_settings(self): config_file = ['conf (*.conf)', 'All files (*)'] file_name, used_filter = QFileDialog().getOpenFileName(caption='Select the GUI config file', filter=';;'.join(config_file)) if file_name: with open(file_name, 'r') as f: try: self._controller.apply_action(NewConfigAction(MapPlotConfig.from_yaml(f.read()))) except yaml.parser.ParserError: pass except yaml.scanner.ScannerError: pass except ValueError: pass
def _select_protocol(self): initial_dir = self._shared_state.base_dir if self.selectedProtocolText.text() != '': initial_dir = self.selectedProtocolText.text() open_file, used_filter = QFileDialog().getOpenFileName( caption='Select the protocol', directory=initial_dir, filter=';;'.join(protocol_files_filters)) if os.path.isfile(open_file): self.selectedProtocolText.setText(open_file) self._shared_state.base_dir = os.path.dirname(open_file)
def _select_output(self): initial_dir = self._shared_state.base_dir if self.selectedOutputText.text() != '': initial_dir = self.selectedOutputText.text() output_file_name, used_filter = QFileDialog().getSaveFileName( caption='Select the output file', directory=initial_dir, filter=';;'.join(image_files_filters)) if output_file_name: self.selectedOutputText.setText(output_file_name)
def _select_mask(self): initial_dir = self._shared_state.base_dir if self.selectedMaskText.text() != '': initial_dir = self.selectedMaskText.text() open_file, used_filter = QFileDialog().getOpenFileName( caption='Select the brain mask', directory=initial_dir, filter=';;'.join(image_files_filters)) if os.path.isfile(open_file): self.selectedMaskText.setText(open_file) self.mask_file_changed() self._shared_state.base_dir = os.path.dirname(open_file)
def _select_output_file(self): output_file_name, used_filter = QFileDialog().getSaveFileName( caption='Select the output file', directory=self._shared_state.base_dir, filter=';;'.join(image_files_filters)) if output_file_name: self.selectedOutputFileText.setText(output_file_name)
def _select_dwi(self): initial_dir = self._shared_state.base_dir if self.selectedDWI.text() != '': initial_dir = self.selectedDWI.text() open_file, used_filter = QFileDialog().getOpenFileName( caption='Select the 4d (diffusion weighted) image', directory=initial_dir, filter=';;'.join(image_files_filters)) if os.path.isfile(open_file): self.selectedDWI.setText(open_file) self._input_data_info.dwi = open_file self._shared_state.base_dir = os.path.dirname(open_file) self.update_output_folder_text()
def _select_protocol(self): initial_dir = self._shared_state.base_dir if self.selectedProtocol.text() != '': initial_dir = self.selectedProtocol.text() open_file, used_filter = QFileDialog().getOpenFileName( caption='Select the protocol', directory=initial_dir, filter=';;'.join(protocol_files_filters)) if os.path.isfile(open_file): self.selectedProtocol.setText(open_file) self._input_data_info.protocol = open_file self._shared_state.base_dir = os.path.dirname(open_file)
def _select_output(self): initial_dir = self._shared_state.base_dir if self.selectedOutputFolder.text() != '': initial_dir = self.selectedOutputFolder.text() output_file_name = QFileDialog().getExistingDirectory( caption='Select the output folder', directory=initial_dir) if output_file_name: self.selectedOutputFolder.setText(output_file_name)
def _select_std_file(self): open_file, used_filter = QFileDialog().getOpenFileName( caption='Select a noise std volume', directory=self._shared_state.base_dir, filter=';;'.join(image_files_filters)) if open_file: self._shared_state.base_dir = os.path.dirname(open_file) self.noiseStd.setText(open_file)
def _select_grad_dev_file(self): open_file, used_filter = QFileDialog().getOpenFileName( caption='Select a gradient deviations volume', directory=self._shared_state.base_dir, filter=';;'.join(image_files_filters)) if open_file: self._shared_state.base_dir = os.path.dirname(open_file) self.gradientDeviations.setText(open_file)
def _select_value_file(self): open_file, used_filter = QFileDialog().getOpenFileName( caption='Select a noise std volume', directory=self._shared_state.base_dir, filter=';;'.join(image_files_filters)) if open_file: self._shared_state.base_dir = os.path.dirname(open_file) self.valueInput.setText(open_file)
def _select_output_folder(self): initial_dir = self._shared_state.base_dir if self.outputFile.text() != '': initial_dir = self.outputFile.text() output_dir = QFileDialog().getExistingDirectory( caption='Select the output folder', directory=initial_dir) if output_dir: self.outputFile.setText(output_dir) self._shared_state.base_dir = output_dir
def test_open_file(window, qtbot, mock): """Test the Open File item of the File submenu. Qtbot clicks on the file sub menu and then navigates to the Open File item. Mock creates an object to be passed to the QFileDialog. """ qtbot.mouseClick(window.file_sub_menu, Qt.LeftButton) qtbot.keyClick(window.file_sub_menu, Qt.Key_Down) mock.patch.object(QFileDialog, 'getOpenFileName', return_value=('', '')) qtbot.keyClick(window.file_sub_menu, Qt.Key_Enter)
def export(self, notes): """ Generic export notes function """ path, _ = QtWidgets.QFileDialog(self).getSaveFileName( self, "Exporter vers", "{}.csv".format(datetime.datetime.now().strftime("%Y-%m-%d")), "CSV Files (*.csv)" ) if path: try: with open(path, "w") as save_file: save_file.write(api.notes.export(notes)) except PermissionError: gui.utils.error("Erreur", "Impossible d'écrire ici")
def add_photo(self): """ Function called to add a photo. Open a QFileDialog and fill self.photo with the selected image """ self.photo_selected = QtWidgets.QFileDialog(self).getOpenFileUrl( self, "Selectionnez une image", settings.IMG_BASE_DIR, "Image Files (*.png *.jpg *.bmp)")[0].path() if self.photo_selected: image = QtGui.QPixmap(self.photo_selected) if not image.isNull(): self.photo.setPixmap(image.scaled(QtCore.QSize(120, 160))) self.on_change()
def export_csv_action(self): """ Called when "Export CSV" is clicked """ path, _ = QtWidgets.QFileDialog(self).getSaveFileName( self, "Exporter vers", "{}.csv".format( datetime.datetime.now().strftime("%Y-%m-%d")), "CSV Files (*.csv)") if path: try: with open(path, "w") as save_file: save_file.write(self._multiple_action(api.notes.export_by_nick, with_coeffs=False)) except PermissionError: error("Erreur", "Impossible d'écrire ici")
def _saveCode(self): codeobj = self._get_selected_codeobj() dialog = QtWidgets.QFileDialog(None, None) dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) if dialog.exec_(): fileNames = dialog.selectedFiles() if len(fileNames) > 0: f = open(fileNames[0], 'wb') f.write(codeobj.final) f.close()
def init_ui(self): self._fileDialog = QFileDialog(self) self._v_layout = QVBoxLayout() self._v_layout.setSpacing(2) self.setLayout(self._v_layout) self._path = "TEXT.png" self._pixmap = QPixmap(self._path) self._btnFile = QPushButton("Open") self._hWidget = QWidget() self._hLayout = QHBoxLayout() self._hWidget.setLayout(self._hLayout) self._image = Image.open(self._path) self._line = QLineEdit() self._hLayout.addWidget(self._btnFile) self._hLayout.addWidget(self._line) size = QSize(160, 90) pix = self._pixmap.scaled(size, transformMode=Qt.SmoothTransformation) self._lbl = QLabel() self._lbl.setPixmap(pix) self._v_layout.addWidget(self._lbl) self._v_layout.addWidget(self._hWidget) self._btnFile.clicked.connect(self.openFilePressed) self._line.setText(pytesseract.image_to_string(Image.open('TEXT.png')))
def select_file(self): if self.init_line_edit.text() == "": script_dir = self.controller.get_script_dir() else: script_dir = self.init_line_edit.text() file_dialog = QtWidgets.QFileDialog() file_dialog.setDirectory(script_dir) file_tuple = file_dialog.getOpenFileName() if not file_tuple[0] == '': self.init_line_edit.setText(file_tuple[0])
def _choose_dir(self): sender = self.sender() if sender.objectName() == 'script_dir_picker': receiver = self.script_dir_input elif sender.objectName() == 'log_dir_picker': receiver = self.log_dir_input directory = receiver.text() dialog = QtWidgets.QFileDialog() folder_path = dialog.getExistingDirectory(self, _("Select Folder"), directory) if not folder_path == '': receiver.setText(folder_path)
def slot_openFileManager(self): open = QFileDialog() self.path = open.getExistingDirectory() self.save_path_lineEdit.setText(self.path) print(self.path)
def on_actionNew_triggered(self): save_file_dialog=QtWidgets.QFileDialog.getSaveFileName(self, "Name of new database", self.work_directory) if save_file_dialog[0]: self.loadDatabase(save_file_dialog[0])
def on_actionOpen_triggered(self): self.fileDialog = QtWidgets.QFileDialog(self) self.fileDialog.setDirectory(self.work_directory) result=self.fileDialog.getOpenFileName() if result[0]: self.loadDatabase(result[0])
def _open_visualization(self): dialog = QtWidgets.QFileDialog(self) dialog.setFileMode(QtWidgets.QFileDialog.ExistingFiles) dialog.setNameFilters(["Processed data file (*.p)", "All Files (*)"]) dialog.exec() fnames = dialog.selectedFiles() if fnames: for fname in fnames: self._processed_file(fname)
def _create_field(self, element): """ :param element: the element newly copied :return: base QWidget, with the source and destination fields built """ def button_clicked(): open_dialog = QFileDialog() if element.tag == "file": file_path = open_dialog.getOpenFileName(self, "Select File:", self.kwargs["package_path"]) if file_path[0]: item_ui.edit_source.setText(relpath(file_path[0], self.kwargs["package_path"])) elif element.tag == "folder": folder_path = open_dialog.getExistingDirectory(self, "Select folder:", self.kwargs["package_path"]) if folder_path: item_ui.edit_source.setText(relpath(folder_path, self.kwargs["package_path"])) parent_element = element.getparent() item = QWidget() item_ui = wizard_files_item.Ui_base() item_ui.setupUi(item) # set initial values item_ui.edit_source.setText(element.properties["source"].value) item_ui.edit_dest.setText(element.properties["destination"].value) item_ui.button_delete.setIcon(QIcon(join(cur_folder, "resources/logos/logo_cross.png"))) # connect the signals item_ui.edit_source.textChanged.connect(element.properties["source"].set_value) item_ui.edit_source.textChanged.connect(element.write_attribs) item_ui.edit_source.textChanged.connect(lambda: self.code_changed.emit(parent_element)) item_ui.edit_dest.textChanged.connect(element.properties["destination"].set_value) item_ui.edit_dest.textChanged.connect(element.write_attribs) item_ui.edit_dest.textChanged.connect(lambda: self.code_changed.emit(parent_element)) item_ui.button_source.clicked.connect(button_clicked) item_ui.button_delete.clicked.connect(item.deleteLater) item_ui.button_delete.clicked.connect(lambda _: parent_element.remove_child(element)) item_ui.button_delete.clicked.connect(lambda: self.code_changed.emit(parent_element)) return item