def saver(self): dlg = QFileDialog() dlg.setWindowIcon(self.window.windowIcon()) options = QFileDialog.options(dlg) options |= QFileDialog.DontUseNativeDialog dlg.setOption(dlg.DontConfirmOverwrite, False) filename = QFileDialog.getSaveFileName( dlg, '', '', 'Text Documents (*.txt);;XML Documents (*.xml)', ".txt", options=options) # type: tuple if filename[ 0]: # if a file name has been supplied (i.e. user entered a name) try: if '.xml' in filename[1]: res = self.write_xml(filename[0]) else: res = self.write_txt(filename[0]) # writes txt files return res except Exception as e: return str(e) else: return 'canceled'
def open_file(self): fileDialog = QFileDialog() file = QFileDialog.getOpenFileName( fileDialog, "Выберите место сохранения файла", "", "All files (*.*);;Наборы изображений (*.ims)", "Наборы изображений (*.ims)", options=fileDialog.options() | QFileDialog.DontUseNativeDialog) if not file[0]: return self.new_file() # Загружаем данные тз нашего файла в xml формате with open(file[0]) as fileObj: xml = fileObj.read() root = etree.fromstring(xml) self.imageSet.filePath = file[0] for elementsXML in root.getchildren(): if elementsXML.tag == "Paths": for element in elementsXML.getchildren(): self.pathListWidget.addItem(element.text) elif elementsXML.tag == "Annotations": for element in elementsXML.getchildren(): imagePath = element.attrib["path"] self.imageSet.imgPaths[imagePath] = SingleImage(imagePath) for imgObject in element.getchildren(): newObject = ObjectInImage() for param in imgObject.getchildren(): if param.tag == "Name": newObject.name = param.text elif param.tag == "Pose": newObject.pose = param.text elif param.tag == "Truncated": newObject.truncated = int(param.text) elif param.tag == "Difficult": newObject.difficult = int(param.text) elif param.tag == "Bndbox": newBoundBox = BoundBox() for coord in param.getchildren(): if coord.tag == "Xmin": newBoundBox.xmin = int(coord.text) elif coord.tag == "Ymin": newBoundBox.ymin = int(coord.text) elif coord.tag == "Xmax": newBoundBox.xmax = int(coord.text) elif coord.tag == "Ymax": newBoundBox.ymax = int(coord.text) newObject.bndbox = newBoundBox self.imageSet.imgPaths[ imagePath].objectsFromImage.append(newObject) elif elementsXML.tag == "Types": for element in elementsXML.getchildren(): self.imageSet.objects[element.text] = len( self.imageSet.objects) self.objectListWidget.addItem(element.text) self.fileName = file[0]
def open_file(self): openDialog = QFileDialog() a = openDialog.getOpenFileName( self, "Выберите файл изображения", "", "All files (*.*);;Microscope scans (*.misc)", "Microscope scans (*.misc)", options=openDialog.options() | QFileDialog.DontUseNativeDialog) for b in a: print(b)
def get_files_images(self, init_dir="", multi_select=True): openDialog = QFileDialog() getFile = openDialog.getOpenFileNames if not multi_select: getFile = openDialog.getOpenFileName files = getFile(self, "Выберите файлы изображения", init_dir, "JPEG (*.jpg);;All files (*)", "JPEG (*.jpg)", options=openDialog.options() | QFileDialog.DontUseNativeDialog) return files[0]
def openFile(self): diag = QFileDialog() options = QFileDialog.options(diag) fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Python Files (*.py)", options=options) if fileName: print(fileName) self.ui.label = QLabel(self) self.ui.pixmap = QPixmap(fileName) self.ui.label.setPixmap(pixmap)
def get_folder_images( self, init_dir="", check_file_mask="*.jpg", caption="Выберите папку с изображениями", answer="В указанной папке не обнаружено файлов изображений. Все равно добавить ее?" ): openDialog = QFileDialog() directory = openDialog.getExistingDirectory( self, caption=caption, directory=init_dir, options=openDialog.options() | QFileDialog.DontUseNativeDialog) if directory and os.path.isdir(directory) and check_file_mask: if not glob.glob(os.path.join(directory, check_file_mask)) \ and not glob.glob(os.path.join(directory, "**", check_file_mask), recursive=True): mBox = QMessageBox() dlgResult = mBox.question(self, "Диалог подтверждения", answer, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if dlgResult == QMessageBox.No: return "" return directory
def openFile(self): diag = QFileDialog() options = QFileDialog.options(diag) path, _ = QFileDialog.getOpenFileName(diag, "QFileDialog.getOpenFileName()", "", ';;'.join(FILE_TYPES), options=options) filename, file_ext = os.path.splitext(path) if path: if file_ext in '.jpg .gif .png': self.workingFileIndex = 0 self.workingFiles = [ os.path.dirname(path) + '/' + file for file in os.listdir(os.path.dirname(path)) if IMAGE_REGEX.match(file) ] for i, file in enumerate(self.workingFiles): if file == path: self.workingFileIndex = i break if not self.workingFiles: self.okayMessageBox('No valid files found in directory') else: self.loadImage(self.workingFiles[self.workingFileIndex]) elif file_ext == '.cbr': # Unrar and open as directory self.rf = rarfile.RarFile(path, mode='r') self.workingFiles = [ f for f in self.rf.infolist() if IMAGE_REGEX.match(f.filename) ] self.loadImage(self.workingFiles[0]) else: self.okayMessageBox("Please use a valid filetype")
def browse(self): """ Open a file dialog and select a user specified file. """ formats = [ "Text - comma separated (*.csv, *)", "Text - tab separated (*.tsv, *)", "Text - all files (*)" ] dlg = QFileDialog( self, windowTitle="Open Data File", acceptMode=QFileDialog.AcceptOpen, fileMode=QFileDialog.ExistingFile ) dlg.setNameFilters(formats) state = self.dialog_state lastdir = state.get("directory", "") lastfilter = state.get("filter", "") if lastdir and os.path.isdir(lastdir): dlg.setDirectory(lastdir) if lastfilter: dlg.selectNameFilter(lastfilter) status = dlg.exec_() dlg.deleteLater() if status == QFileDialog.Accepted: self.dialog_state["directory"] = dlg.directory().absolutePath() self.dialog_state["filter"] = dlg.selectedNameFilter() selected_filter = dlg.selectedNameFilter() path = dlg.selectedFiles()[0] # pre-flight check; try to determine the nature of the file mtype = _mime_type_for_path(path) if not mtype.inherits("text/plain"): mb = QMessageBox( parent=self, windowTitle="", icon=QMessageBox.Question, text="The '{basename}' may be a binary file.\n" "Are you sure you want to continue?".format( basename=os.path.basename(path)), standardButtons=QMessageBox.Cancel | QMessageBox.Yes ) mb.setWindowModality(Qt.WindowModal) if mb.exec() == QMessageBox.Cancel: return # initialize dialect based on selected extension if selected_filter in formats[:-1]: filter_idx = formats.index(selected_filter) if filter_idx == 0: dialect = csv.excel() elif filter_idx == 1: dialect = csv.excel_tab() else: dialect = csv.excel_tab() header = True else: try: dialect, header = sniff_csv_with_path(path) except Exception: # pylint: disable=broad-except dialect, header = csv.excel(), True options = None # Search for path in history. # If found use the stored params to initialize the import dialog items = self.itemsFromSettings() idx = index_where(items, lambda t: samepath(t[0], path)) if idx is not None: _, options_ = items[idx] if options_ is not None: options = options_ if options is None: if not header: rowspec = [] else: rowspec = [(range(0, 1), RowSpec.Header)] options = Options( encoding="utf-8", dialect=dialect, rowspec=rowspec) dlg = CSVImportDialog( self, windowTitle="Import Options", sizeGripEnabled=True) dlg.setWindowModality(Qt.WindowModal) dlg.setPath(path) dlg.setOptions(options) status = dlg.exec_() dlg.deleteLater() if status == QDialog.Accepted: self.set_selected_file(path, dlg.options())
def browse(self): """ Open a file dialog and select a user specified file. """ formats = [ "Text - comma separated (*.csv, *)", "Text - tab separated (*.tsv, *)", "Text - all files (*)" ] dlg = QFileDialog( self, windowTitle="Open Data File", acceptMode=QFileDialog.AcceptOpen, fileMode=QFileDialog.ExistingFile ) dlg.setNameFilters(formats) state = self.dialog_state lastdir = state.get("directory", "") lastfilter = state.get("filter", "") if lastdir and os.path.isdir(lastdir): dlg.setDirectory(lastdir) if lastfilter: dlg.selectNameFilter(lastfilter) status = dlg.exec_() dlg.deleteLater() if status == QFileDialog.Accepted: self.dialog_state["directory"] = dlg.directory().absolutePath() self.dialog_state["filter"] = dlg.selectedNameFilter() selected_filter = dlg.selectedNameFilter() path = dlg.selectedFiles()[0] # pre-flight check; try to determine the nature of the file mtype = _mime_type_for_path(path) if not mtype.inherits("text/plain"): mb = QMessageBox( parent=self, windowTitle="", icon=QMessageBox.Question, text="The '{basename}' may be a binary file.\n" "Are you sure you want to continue?".format( basename=os.path.basename(path)), standardButtons=QMessageBox.Cancel | QMessageBox.Yes ) mb.setWindowModality(Qt.WindowModal) if mb.exec() == QMessageBox.Cancel: return # initialize dialect based on selected extension if selected_filter in formats[:-1]: filter_idx = formats.index(selected_filter) if filter_idx == 0: dialect = csv.excel() elif filter_idx == 1: dialect = csv.excel_tab() else: dialect = csv.excel_tab() header = True else: try: dialect, header = sniff_csv_with_path(path) except Exception: dialect, header = csv.excel(), True options = None # Search for path in history. # If found use the stored params to initialize the import dialog items = self.itemsFromSettings() idx = index_where(items, lambda t: samepath(t[0], path)) if idx is not None: _, options_ = items[idx] if options_ is not None: options = options_ if options is None: if not header: rowspec = [] else: rowspec = [(range(0, 1), RowSpec.Header)] options = Options( encoding="utf-8", dialect=dialect, rowspec=rowspec) dlg = CSVImportDialog( self, windowTitle="Import Options", sizeGripEnabled=True) dlg.setWindowModality(Qt.WindowModal) dlg.setPath(path) dlg.setOptions(options) status = dlg.exec_() dlg.deleteLater() if status == QDialog.Accepted: self.set_selected_file(path, dlg.options())
def _save_file_dialog(filters, parent, base_directory): dialog = QFileDialog() options = dialog.options() options |= dialog.DontUseCustomDirectoryIcons file_name, res = dialog.getSaveFileName(parent, _('Save'), base_directory, filters, options=options) return file_name
def open_settings_file_dialog(parent, base_path=''): dialog = QFileDialog(parent) options = dialog.options() options |= dialog.DontUseCustomDirectoryIcons file_name,res = dialog.getOpenFileName(parent, _('File selection'), base_path, _("Settings file (*.set)")) return file_name, res
def open_any_directory_dialog(parent, base_directory=''): dialog = QFileDialog(parent) options = dialog.options() options |= dialog.DontUseCustomDirectoryIcons dir_name = dialog.getExistingDirectory(parent, _('Directory selection'), base_directory, options) return dir_name
def save_file(self, save_dlg=True): if self.pathListWidget.count() == 0: return if save_dlg or not self.fileName: fileDialog = QFileDialog() file = QFileDialog.getSaveFileName( fileDialog, "Выберите место сохранения файла", "", "All files (*.*);;Наборы изображений (*.ims)", "Наборы изображений (*.ims)", options=fileDialog.options() | QFileDialog.DontUseNativeDialog) if file[0]: ext = os.path.splitext(file[0]) if ext[1] == ".ims": self.fileName = file[0] else: self.fileName = ext[0] + ".ims" if os.path.exists(self.fileName): messageBox = QMessageBox() dlgResult = QMessageBox.question( messageBox, "Confirm Dialog", "Файл уже существует. Хотите его перезаписать?" + "Это удалит данные в нем", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if dlgResult == QMessageBox.No: return else: return # Записываем данные в наш файл в xml формате if self.fileName: root = xmlET.Element("ImageSet") pathsElement = xmlET.Element("Paths") root.append(pathsElement) for i in range(self.pathListWidget.count()): pathElement = xmlET.SubElement(pathsElement, "Path") pathElement.text = self.pathListWidget.item(i).text() annotationsElement = xmlET.Element("Annotations") root.append(annotationsElement) for key, value in self.imageSet.imgPaths.items(): fileElement = xmlET.SubElement(annotationsElement, "File") fileElement.set("path", key) for obj in value.objectsFromImage: objElement = xmlET.SubElement(fileElement, "Object") objName = xmlET.SubElement(objElement, "Name") objName.text = obj.name objPose = xmlET.SubElement(objElement, "Pose") objPose.text = obj.pose objTruncated = xmlET.SubElement(objElement, "Truncated") objTruncated.text = str(obj.truncated) objDifficult = xmlET.SubElement(objElement, "Difficult") objDifficult.text = str(obj.difficult) objBndbox = xmlET.SubElement(objElement, "Bndbox") objXMin = xmlET.SubElement(objBndbox, "Xmin") objXMin.text = str(obj.bndbox.xmin) objYMin = xmlET.SubElement(objBndbox, "Ymin") objYMin.text = str(obj.bndbox.ymin) objXMax = xmlET.SubElement(objBndbox, "Xmax") objXMax.text = str(obj.bndbox.xmax) objYMax = xmlET.SubElement(objBndbox, "Ymax") objYMax.text = str(obj.bndbox.ymax) pathsElement = xmlET.Element("Types") root.append(pathsElement) for obj in self.imageSet.objects.keys(): pathElement = xmlET.SubElement(pathsElement, "Type") pathElement.text = obj tree = xmlET.ElementTree(root) with open(self.fileName, "w"): tree.write(self.fileName)