def on_load_model(self): dialog = QFileDialog(caption="选择编码网络", directory="../models/") if dialog.exec_(): fileName = dialog.selectedFiles() self.encode_path = fileName[0] self.ui.TextEdit.appendPlainText("编码网络模型:" + fileName[0]) dialog = QFileDialog(caption="选择关系网络", directory="../models/") if dialog.exec_(): fileName = dialog.selectedFiles() self.relation_path = fileName[0] self.ui.TextEdit.appendPlainText("关系网络模型:" + fileName[0]) self.ui.TextEdit.appendPlainText("--加载网络模型--") self.feature_encoder.cuda(GPU) self.relation_network.cuda(GPU) if os.path.exists(self.encode_path): self.feature_encoder.load_state_dict(torch.load(self.encode_path)) self.ui.TextEdit.appendPlainText("--成功加载编码模型--") if os.path.exists(self.relation_path): self.relation_network.load_state_dict( torch.load(self.relation_path)) self.ui.TextEdit.appendPlainText("--成功加载关系模型--")
def browseForAPILocation(self) -> None: """ Opens a file dialog when the user clicks on the "..." button to choose a project directory. The user will only be able to select folders, and when a folder is selected, the value will be placed into the read-only text editor to the left. The default location is the current project location. :return: None :rtype: NoneType """ if getPythonBitness() == 32: openDir = "C:/Program Files (x86)" else: openDir = "C:/Program Files" openDir = os.path.abspath(openDir) fileDialog = QFileDialog() fileDialog.setFileMode(QFileDialog.Directory) fileDialog.setDirectory(openDir) fileDialog.fileSelected.connect( lambda url: self.ui.apiLocation.setText(url)) fileDialog.exec_()
def _browseApplicationFile(self) -> None: """ Opens a file dialog when the user clicks on the "..." button to choose a target application. The dialog that pops up doesn't restrict what file the user selects, but before creating the project, the file will be checked for correct bitness, and to make sure that it's an executable file. The path to the file will be placed into the read-only text editor to the left. :return: None :rtype: NoneType """ # determine which programs directory to open based on the bitness of Facile. if getPythonBitness() == 32: openDir = "C:/Program Files (x86)" else: openDir = "C:/Program Files" openDir = os.path.abspath(openDir) fileDialog = QFileDialog() fileDialog.setFileMode(QFileDialog.ExistingFile) fileDialog.setDirectory(openDir) fileDialog.fileSelected.connect( lambda url: self.ui.executable_file_edit.setText(url)) fileDialog.exec_()
def browseForInterpreterLocation(self) -> None: """ Opens a file dialog when the user clicks on the "..." button to choose a target application. The dialog that pops up doesn't restrict what file the user selects, but before creating the project, the file will be checked for correct bitness, and to make sure that it's an executable file. The path to the file will be placed into the read-only text editor to the left. The default location is the default python location on user's end. :return: None :rtype: NoneType """ if getPythonBitness() == 32: openDir = "C:/Program Files (x86)" else: openDir = "C:/Program Files" openDir = os.path.abspath(openDir) fileDialog = QFileDialog() fileDialog.setFileMode(QFileDialog.ExistingFile) fileDialog.setDirectory(openDir) fileDialog.fileSelected.connect( lambda url: self.ui.interpreterLocation.setText(url)) fileDialog.exec_()
def bnr_load_dialog(self) -> bool: supportedFormats = { "*.bmp": "Windows Bitmap", "*.bnr": "Nintendo Banner", "*.ico": "Windows Icon", "*.jpg|*.jpeg": "JPEG Image", "*.png": "Portable Network Graphics", "*.ppm": "Portable Pixmap", "*.tga": "BMP Image", "*.tif": "Tagged Image", "*.webp": "WEBP Image" } _allsupported = " ".join( [" ".join(k.split("|")) for k in supportedFormats]) _filter = f"All supported formats ({_allsupported});;" + ";;".join([ f"{supportedFormats[k]} ({' '.join(k.split('|'))})" for k in supportedFormats ]) + ";;All files (*)" dialog = QFileDialog(parent=self, caption="Open Image", directory=str(self.bnrImagePath.parent if self. bnrImagePath else Path.home()), filter=_filter) dialog.setFileMode(QFileDialog.ExistingFile) if dialog.exec_() != QFileDialog.Accepted: return False, "" self.bnrImagePath = Path(dialog.selectedFiles()[0]).resolve() if self.bnrImagePath.is_file(): if self.bnrImagePath.suffix == ".bnr": self.bnrMap.rawImage = BytesIO( self.bnrImagePath.read_bytes()[0x20:0x1820]) self.bnr_update_info() else: with Image.open(self.bnrImagePath) as image: if image.size != (96, 32): dialog = JobWarningDialog( f"Resizing image of size {image.size} to match BNR size (96, 32)", self) dialog.exec_() self.bnrMap.rawImage = image pixmap = ImageQt.toqpixmap(self.bnrMap.getImage()) pixmap = pixmap.scaled( self.ui.bannerImageView.geometry().width() - 1, self.ui.bannerImageView.geometry().height() - 1, Qt.KeepAspectRatio) self.ui.bannerImageView.setPixmap(pixmap) return True, "" else: return False, "The file does not exist!"
def browseForFile_load(self) -> None: """ Opens a file dialog when the user clicks on the "Save As..." option to choose a file to save to. """ fileDialog = QFileDialog() fileDialog.setFileMode(QFileDialog.ExistingFile) fileDialog.setDirectory(os.getcwd()) fileDialog.setNameFilter("Project (*.proj)") fileDialog.fileSelected.connect(lambda url: self.loadFile(url)) fileDialog.exec_()
def _browseForExistingProject(self) -> None: """ Opens a file dialog when the user clicks on the existing project's "..." button to choose an existing .fcl file. :return: None :rtype: NoneType """ fileDialog = QFileDialog() fileDialog.setFileMode(QFileDialog.ExistingFile) fileDialog.setDirectory(expanduser("~")) fileDialog.setNameFilter("Facile Project File (*.fcl)") fileDialog.fileSelected.connect( lambda url: self._setOldProject(Project.load(url))) fileDialog.exec_()
def export(self): """ Export the story-creator data files to a user-selected locaion. """ fileBrowser = QFileDialog() fileBrowser.setFileMode(QFileDialog.Directory) fileBrowser.setViewMode(QFileDialog.Detail) fileBrowser.setOption(QFileDialog.ShowDirsOnly, True) if fileBrowser.exec_(): paths = fileBrowser.selectedFiles() else: print("Cancelled") return print("Copying data to " + str(paths[0]) + "/exportdata") try: copytree(json_reader.buildPath("data"), str(paths[0]) + "/exportdata") except OSError as e: print(e) popup( "Error in copying files. There is a file in the selected directory that has the same name " "as a Story Creator file.\n\nFiles are copied to " + str(paths[0]) + "/exportdata" + ". Please " "ensure this directory does not already exist.", "Critical") return print("Successfully copied files") popup("Files exported successfully!", "Information")
def save_generic_to_folder( self, parent=None, caption="Save to folder...", filter=None, callback: Callable[[Controller, Path, Tuple], None] = None, args=() ) -> Tuple[bool, str]: if filter is None: filter = "Any folder" dialog = QFileDialog( parent=parent, caption=caption, directory=str( self.genericPath.parent if self.genericPath else Path.home()), filter=filter) dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec_() != QFileDialog.Accepted: return False self.genericPath = Path(dialog.selectedFiles()[0]) if callback: callback(self, self.genericPath, *args) return True else: return True
def openFile(self): # file selection dialog dialog = QFileDialog() dialog.setDirectory(self.path_excel) dialog.setNameFilter(self.filters) if not dialog.exec_(): return # read selected file filename: str = dialog.selectedFiles()[0] if self.sheets is not None: del self.sheets self.sheets: ExcelSPC = ExcelSPC(filename) # update path to open self.path_excel = os.path.dirname(filename) # check if sheets have valid format or not if self.sheets.valid is not True: QMessageBox.critical(self, 'Error', 'Not appropriate format!') self.sheets = None return # update application title self.setAppTitle(filename) # create new tab self.createTabs()
def loadfile(self): f_dialog = QFileDialog(self) f_dialog.setFileMode(QFileDialog.ExistingFile) f_dialog.setNameFilter(self.tr("Dicom File (*.dcm)")) f_dialog.setViewMode(QFileDialog.Detail) if f_dialog.exec_(): self.file_path = f_dialog.selectedFiles()[0] self.ui.val_file_path.setPlainText(str(self.file_path)) self.file_name = os.path.basename(self.file_path) if self.file_path is None: self.log("[LOAD::FAIL]") return None self.dataset = pydicom.dcmread(self.file_path) self.reslope = int(self.dataset.RescaleSlope) self.reinter = int(self.dataset.RescaleIntercept) self.hu_data = self.reslope * self.dataset.pixel_array + self.reinter self.log("[LOAD::PASS] " + self.file_name) self.file_load_flag = True self.view()
def question_directory(self): start_dir = pathlib.Path.home() other = start_dir.joinpath(START_DIR) if other.is_dir(): start_dir = other dialog = QFileDialog(self, caption="Open Questions Directory", directory=start_dir.as_posix()) dialog.setFileMode(QFileDialog.Directory) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): dir_names = dialog.selectedFiles() dir_path = pathlib.Path(dir_names[0]) files = [] if len(self.q_types) < 1 or '*' in self.q_types: files = dir_path.iterdir() else: for ext in self.q_types: files.extend(dir_path.glob(ext)) for question in files: last = self.find_last_row('question') if last == -1: self.add_item(question=str(question)) else: self.edit_item(index=last, question=str(question))
def openDlg(mainWidget, ask=True): """ Returns a file name or None. @param mainWidget: @type mainWidget: @param ask: @type ask: @return: @rtype: """ if ask and mainWidget.label.img.isModified: ret = saveChangeDialog(mainWidget.label.img) if ret == QMessageBox.Yes: try: saveDlg(mainWidget.label.img, mainWidget) except (ValueError, IOError) as e: dlgWarn(str(e)) return elif ret == QMessageBox.Cancel: return # don't ask again for saving mainWidget.label.img.isModified = False lastDir = str(mainWidget.settings.value('paths/dlgdir', '.')) dlg = QFileDialog( mainWidget, "select", lastDir, " *".join(IMAGE_FILE_EXTENSIONS) + " *".join(RAW_FILE_EXTENSIONS)) if dlg.exec_(): filenames = dlg.selectedFiles() newDir = dlg.directory().absolutePath() mainWidget.settings.setValue('paths/dlgdir', newDir) return filenames[0]
def f(): from bLUeTop.QtGui1 import window lastDir = str(window.settings.value('paths/dlgdir', '.')) filter = "Images ( *" + " *".join(IMAGE_FILE_EXTENSIONS) + ")" dlg = QFileDialog(window, "select", lastDir, filter) if dlg.exec_(): filenames = dlg.selectedFiles() newDir = dlg.directory().absolutePath() window.settings.setValue('paths/dlgdir', newDir) self.sourceImage = QImage(filenames[0]) self.updateSource() """ # scale img while keeping its aspect ratio # into a QPixmap having the same size than self.layer sourcePixmap = QPixmap.fromImage(self.sourceImage).scaled(self.layer.size(), Qt.KeepAspectRatio) self.sourceSize = sourcePixmap.size() self.sourcePixmap = QPixmap(self.layer.size()) self.sourcePixmap.fill(Qt.black) qp = QPainter(self.sourcePixmap) qp.drawPixmap(QPointF(), sourcePixmap) # (QRect(0, 0, sourcePixmap.width(), sourcePixmap.height()), sourcePixmap) qp.end() self.sourcePixmapThumb = self.sourcePixmap.scaled(self.pwSize, self.pwSize, aspectMode=Qt.KeepAspectRatio) self.widgetImg.setPixmap(self.sourcePixmapThumb) self.widgetImg.setFixedSize(self.sourcePixmapThumb.size()) self.layer.sourceFromFile = True """ self.widgetImg.show()
def _fileChooser(): fdia = QFileDialog() fdia.setNameFilter("air apps(*.air)") if (fdia.exec_()): fchoosed = fdia.selectedFiles()[0] self.inp_file.setText(fchoosed) self.updateScreen()
def FilesOpen06(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): dirName = dialog.selectedFiles() UI_set.TBrowser.setText(str(dirName))
def action_load_files(self): log.info("Loading .nif files ...") self.toggle(False) self.progress_bar.setMinimum(0) self.progress_bar.setMaximum(0) file_dialog = QFileDialog() file_dialog.setFileMode(QFileDialog.DirectoryOnly) file_dialog.setDirectory(self.source_folder) if file_dialog.exec_(): scan_dirs = file_dialog.selectedFiles() if len(scan_dirs) >= 1: self.source_folder = scan_dirs[0] else: self.source_folder = file_dialog.directory() if self.source_folder: log.info("Scanning directory : " + self.source_folder) CONFIG.set("DEFAULT", "SourceFolder", self.source_folder), save_config() worker = Worker(self.load_files) worker.signals.progress.connect(self.update_nif_files) worker.signals.result.connect(self.finish_load_action) QThreadPool.globalInstance().start(worker)
def on_select_folders(self): dialog = QFileDialog(directory="../../datas/omniglot_resized") dialog.setFileMode(QFileDialog.Directory) self.image_folders = [] for i in range(5): if dialog.exec_(): fileName = dialog.selectedFiles() self.image_folders.append(fileName[0]) self.ui.TextEdit.appendPlainText(" class:"+ str(i)+ " "+ fileName[0].split("/")[-2] + '/' + fileName[0].split("/")[-1]) train_image_root = [os.path.join(fold, os.listdir(fold)[i]).replace("\\", "/") for fold in self.image_folders for i in np.random.randint(0, 19, 1)] query_image_root = [os.path.join(fold, os.listdir(fold)[i]).replace("\\", "/") for fold in self.image_folders for i in range(20)] query_image_root = list(set(query_image_root) - set(train_image_root)) #query = [query_image_root[i] for i in np.random.randint(0, 94, TEST_NUMS)] self.query_image_root = query_image_root self.train_image_root = train_image_root for i in range(5): image = QtGui.QPixmap(train_image_root[i]).scaled(self.ui.train_img1.width(), self.ui.train_img1.height()) self.pix_train_images[i].setPixmap(image)
def open_dialog_for_directory(mode: str): """ Function wrapper to open file dialogs for selecting mkv files :return: a list of selected files """ if mode == "single": extensions = ["/*.mkv", "/*.ass", "/*.srt", "/*.flac", "/*.ac3"] elif mode == "batch": extensions = ["/*.mkv"] else: logger.error("Invalid mode") return None file_list = [] dialog = QFileDialog() dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec_(): directory_name = dialog.selectedFiles() logger.debug(directory_name) for extension in extensions: logger.debug("Searching inside " + directory_name[0] + extension) file_list.extend(glob.glob(directory_name[0] + extension)) for file in file_list: logger.info(file + " found") logger.info(str(len(file_list)) + " files found.") return file_list
def selectImagePath(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.DirectoryOnly) dialog.selectFile(self.ui.lineEdit_2.text()) dialog.setWindowTitle('Select Directory Where Images Are Stored') if dialog.exec_(): self.ui.lineEdit_2.setText(dialog.selectedFiles()[0])
def select_folder(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) if dialog.exec_(): selected_dir = dialog.selectedFiles()[0] self.folder_address_input.setText(selected_dir) self.update_model(selected_dir)
def show_dialog(self): """Show the file browser dialog.""" dialog = QFileDialog(self) dialog.setNameFilter(self.file_filter) file_mode = [ QFileDialog.AnyFile, QFileDialog.ExistingFile, QFileDialog.Directory, ][self.file_mode] dialog.setFileMode(file_mode) dialog.setModal(True) if self.cache: dialog.setHistory(self.cache.stringList()) for value in self.cache.stringList(): if os.path.exists(value): if os.path.isfile(value): directory = os.path.dirname(value) dialog.selectFile(value) else: directory = value dialog.setDirectory(directory) break if dialog.exec_() == QDialog.Accepted: path = dialog.selectedFiles() if path: self._push(path[0])
def askSaveFileName(parent=None, title=bdstr.fn2Use, filter="", dir=""): """Uses `QFileDialog` to ask the names of a single file where something will be saved (the file may not exist) Parameters (all optional): parent (default None): the parent of the window title: the window title filter: the filter to be used when displaying files dir: the initial directory Output: return the filename or an empty string depending if the user selected "Ok" or "Cancel" """ dialog = QFileDialog(parent, title, dir, filter) dialog.setFileMode(QFileDialog.AnyFile) dialog.setOption(QFileDialog.DontConfirmOverwrite, True) if dialog.exec_(): fileNames = dialog.selectedFiles() try: return fileNames[0] except IndexError: return "" else: return ""
def OnLoadScript(self, event): dlg = QFileDialog() if dlg.exec_(): self.filename = dlg.selectedFiles()[0] self.ui.label_ExpScriptFile.setText(os.path.split(self.filename)[-1])
def click_add_files(self): files_dialog = QFileDialog() files_dialog.setNameFilter("Images (*.jpg *.jpeg *.bmp *.png *.tiff)") files_dialog.setFileMode(QFileDialog.ExistingFiles) if files_dialog.exec_(): files = files_dialog.selectedFiles() self.add_items(files)
def iso_load_root_dialog(self) -> Tuple[bool, str]: dialog = QFileDialog( parent=self, caption="Open Gamecube Root", directory=str( self.rootPath.parent if self.rootPath else Path.home()), filter="All folders (*)") dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec_() != QFileDialog.Accepted: return False, "" selected = Path(dialog.selectedFiles()[0]).resolve() if not selected.exists(): return False, "The path does not exist!" self.rootPath = selected if self.rootPath.is_dir(): self._fromIso = False iso = GamecubeISO.from_root(self.rootPath, True) iso.onPhysicalJobStart = self._iso_start_callback iso.onPhysicalJobComplete = self._iso_complete_callback iso.onPhysicalJobExit = self._iso_exit_callback iso.onVirtualJobStart = self._iso_start_callback iso.onVirtualJobComplete = self._iso_complete_callback iso.onVirtualJobExit = self._iso_exit_callback self.iso = iso self.bnrMap = self.iso.bnr self.ui.bannerComboBox.clear() self.ui.bannerComboBox.addItems( sorted([ p.name for p in self.iso.rchildren() if fnmatch(p.name, "*.bnr") ], key=str.lower)) self.ui.actionClose.setEnabled(True) self.ui.actionSave.setEnabled(True) self.ui.actionRebuild.setEnabled(True) self.ui.actionExtract.setEnabled(False) self.update_all() else: return False, "The file does not exist!" if self.iso.is_dolphin_root(): self.setWindowTitle( f"{self.get_window_title()} - {self.iso.bootheader.gameName} (root)" ) elif self.iso.is_gcr_root(): self.setWindowTitle( f"{self.get_window_title()} - {self.iso.bootheader.gameName} (GCR root)" ) else: return False, f"{self.rootPath} is not a valid root folder!" return True, ""
def savePushed(self): """ Let the user select a TCX file to save to. Store the data. """ self.saveButton.setEnabled(False) tcx_dir_key = "file/tcx_dir" tcx_dir = self.settings.value(tcx_dir_key, ".") use_file_date = self.useFileDate.isChecked() if use_file_date: local_time = self.in_file_info.created().toPython() else: local_time = self.workoutTime.dateTime().toPython() utc_zone = tz.tzutc() local_zone = tz.tzlocal() local_time = local_time.replace(tzinfo=local_zone) start_time = local_time.astimezone(utc_zone) dialog = QFileDialog(self) dialog.selectFile(self.in_file_info.baseName() + ".tcx") dialog.setDirectory(tcx_dir) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) filename = None if dialog.exec_(): filenames = dialog.selectedFiles() if len(filenames): filename = filenames[0] if not filename: # User cancel return power_adjust = self.powerAdjustment.value() self.mpower.set_power_adjust(power_adjust) self.mpower.set_interpolation(self.checkBoxInterpolate.isChecked()) mass = self.doubleSpinBoxRiderWeight.value( ) + self.doubleSpinBoxBikeWeight.value() if self.comboBoxUnits.currentText() == "lbs": mass *= self.lbs_to_kg self.mpower.set_physics(self.checkBoxPhysics.isChecked(), mass) thread_result = {'message': None, 'status': False} t = threading.Thread(target=self.saveThread, args=(filename, start_time, thread_result)) t.start() t.join() self.alert(thread_result['message']) info = QFileInfo(filename) tcx_dir = info.absoluteDir().path() self.settings.setValue(tcx_dir_key, tcx_dir)
def __browse_for_course(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter('*.lean') if dialog.exec_(): course_file_path = Path(dialog.selectedFiles()[0])
def select_location(self): dialog = QFileDialog(self, 'File Storage Location', self.settings['file_storage_location']) dialog.setFileMode(QFileDialog.DirectoryOnly) if dialog.exec_() == QDialog.Accepted: new_path = dialog.selectedFiles()[0] UserSettingsSignal.put.emit('file_storage_location', new_path) self.file_label.setText(new_path)
def OnLoadScript(self): dlg = QFileDialog() dlg.setNameFilter("Script (*.ipynb)") if dlg.exec_(): _script = dlg.selectedFiles()[0] self.exp.set_analysis_script(_script) self.clear_windows() self.set_windows()
def open(self): fileDialog = QFileDialog(self) supportedMimeTypes = QMediaPlayer.supportedMimeTypes() if not supportedMimeTypes: supportedMimeTypes.append("video/x-msvideo") # AVI fileDialog.setMimeTypeFilters(supportedMimeTypes) moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation) fileDialog.setDirectory(moviesLocation) if fileDialog.exec_() == QDialog.Accepted: self.playlist.addMedia(fileDialog.selectedUrls()[0]) self.player.play()